Created
October 10, 2013 14:33
-
-
Save fer-ri/6919367 to your computer and use it in GitHub Desktop.
BaseModel to extend Laravel Model and add some validation
http://forums.laravel.io/viewtopic.php?pid=45695#p45695
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // models/BaseModel.php | |
| class BaseModel extends Eloquent | |
| { | |
| /** | |
| * Errors returned by the validator. | |
| * | |
| * @var Object | |
| */ | |
| public $errors; | |
| /** | |
| * Enables us to turn the validator on or off completely. | |
| * | |
| * @var boolean | |
| */ | |
| public $enableValidator = true; | |
| /** | |
| * An array of items to be removed from input before saving. | |
| * | |
| * @var array | |
| */ | |
| private $cleanDefaults = array('_token', '_method', 'password_confirmation'); | |
| /** | |
| * Hooks into the boot function of eloquent to monitor | |
| * when events are being carried out. | |
| * | |
| * @return mixed | |
| */ | |
| public static function boot() | |
| { | |
| // if we're saving the model, validate it first. | |
| static::saving(function($model){ | |
| return $model->validate(); | |
| }); | |
| } | |
| /** | |
| * Validator method. Takes the rules of the model and applies them. | |
| * | |
| * @return boolean | |
| */ | |
| public function validate(array $rules = array()) | |
| { | |
| // if the validator isn't enabled or there are no rules return true. | |
| if(!$this->enableValidator || !isset(static::$rules)) return true; | |
| $rules = self::processRules($rules ? $rules : static::$rules); | |
| $validator = Validator::make($this->attributes, $rules, static::$messages ?: array()); | |
| // the the model attributes are valid, return true. | |
| if ($validator->passes()) { | |
| $this->cleanAttributes(); | |
| $this->autoHash(); | |
| return true; | |
| } | |
| // set the error messages to be returned. | |
| $this->errors = $validator->messages(); | |
| return false; | |
| } | |
| /** | |
| * Process validation rules and replace ID's in "unique" rules. | |
| * | |
| * @param array $rules | |
| * @return array $rules | |
| */ | |
| protected function processRules(array $rules) | |
| { | |
| // get the model's ID. | |
| // If the ID is null, it's a new Model, so let's strip out the id completely. | |
| $id = $this->getKey(); | |
| $replacement = $id == null ? "" : "," . $id; | |
| array_walk($rules, function(&$item) use ($replacement) | |
| { | |
| // Replace placeholders | |
| $item = stripos($item, ',:id:') !== false ? str_ireplace(',:id:', $replacement, $item) : $item; | |
| }); | |
| return $rules; | |
| } | |
| /** | |
| * Removes any attributes from the model that should not be saved to the database. | |
| * | |
| * @return void | |
| */ | |
| public function cleanAttributes() | |
| { | |
| $cleaning = isset(static::$clean) ? array_merge(static::$clean, $this->cleanDefaults) : $this->cleanDefaults; | |
| foreach($cleaning as $attr): | |
| unset($this->$attr); | |
| endforeach; | |
| } | |
| /** | |
| * Automatically hashes specified attributes before their saved to the database. | |
| * | |
| * @return void | |
| */ | |
| public function autoHash() | |
| { | |
| if (isset(static::$autoHash)) { | |
| foreach(static::$autoHash as $attr): | |
| // We should only hash attributes in the model that have changed. | |
| // We should ignore blank attributes - for example, the password may not have changed | |
| // so we don't want to change it. | |
| if ($this->getOriginal($attr) != $this->$attr && strlen($this->$attr) > 0) { | |
| $this->$attr = Hash::make($this->$attr); | |
| } | |
| endforeach; | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // controllers/MyController.php | |
| /** | |
| * Store a newly created resource in storage. | |
| * | |
| * @return Response | |
| */ | |
| public function store() | |
| { | |
| $input = Input::all(); | |
| $user = new User(Input::all()); | |
| if ($user->save()) { | |
| return Redirect::route('admin.users.index'); | |
| } | |
| return Redirect::route('admin.users.create')->withInput()->withErrors($user->errors); | |
| } | |
| /** | |
| * Update the specified resource in storage. | |
| * | |
| * @param int $id | |
| * @return Response | |
| */ | |
| public function update($id) | |
| { | |
| // see if the user exists. If not, redirect with errors. | |
| $user = User::find($id); | |
| if(is_null($user)){ | |
| Notification::error("This user cannot be found."); | |
| return Redirect::route('admin.users'); | |
| } | |
| $input = Input::all(); | |
| // if the user validates & updates successfully, go back to the user's list. | |
| // otherwise, return some errors. | |
| if ( $user->update($input) ) { | |
| Notification::success("This user has been updated"); | |
| return Redirect::route('admin.users.index'); | |
| } else { | |
| return Redirect::route('admin.users.edit', $id)->withErrors( $user->errors )->withInput(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // models/User.php | |
| use Illuminate\Auth\UserInterface; | |
| use Illuminate\Auth\Reminders\RemindableInterface; | |
| class User extends BaseModel implements UserInterface, RemindableInterface { | |
| /** | |
| * The database table used by the model. | |
| * | |
| * @var string | |
| */ | |
| protected $table = 'users'; | |
| /** | |
| * Ensure our records aren't permanantly deleted - only hidden. | |
| * | |
| * @var boolean | |
| */ | |
| protected $softDeletes = true; | |
| /** | |
| * The attributes excluded from the model's JSON form. | |
| * | |
| * @var array | |
| */ | |
| protected $hidden = array('password'); | |
| /** | |
| * Guarded attributes on the model | |
| * | |
| * @var array | |
| */ | |
| protected $guarded = array(); | |
| /** | |
| * Validation Rules | |
| * | |
| * @var array | |
| */ | |
| public static $rules = array( | |
| 'forename' => 'required|between:2,40', | |
| 'surname' => 'required|between:2,40', | |
| 'email' => 'email|required|between:6,150|unique:users,email,:id:', | |
| 'username' => 'required|between:4,20|unique:users,username,:id:', | |
| 'password' => 'required_without:id|confirmed|min:6', | |
| 'password_confirmation' => 'required_with:password|min:6', | |
| ); | |
| /** | |
| * Custom validation messages | |
| * | |
| * @var array | |
| */ | |
| public static $messages = array(); | |
| /** | |
| * Attributes to automatically clean from the Input | |
| * | |
| * @var array | |
| */ | |
| public static $clean = array(); | |
| /** | |
| * Attributes to be automatically hashed when saving | |
| */ | |
| public static $autoHash = array('password'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment