Last active
July 20, 2019 11:14
-
-
Save fredyounan/8328483 to your computer and use it in GitHub Desktop.
Eloquent boot method
This file contains 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
class Post extends Eloquent { | |
/** | |
* This is a useful switch to temporarily turn of automatic model validation. | |
*/ | |
public static $autoValidate = true; | |
/** | |
* The rules to use for the model validation. | |
* Define your validation rules here. | |
* | |
* @var array | |
*/ | |
protected static $rules = array(); | |
protected static function boot() | |
{ | |
// This is an important call, makes sure that the model gets booted | |
// properly! | |
parent::boot(); | |
// You can also replace this with static::creating or static::updating | |
// if you want to call specific validation functions for each case. | |
static::saving(function($model) | |
{ | |
if($model::$autoValidate) | |
{ | |
// If autovalidate is true, validate the model on create | |
// and update. | |
return $model->validate(); | |
} | |
}); | |
// cause a delete of a post to cascade to children so they are also deleted | |
static::deleted(function($post) | |
{ | |
$post->images()->delete(); | |
$post->descriptions()->delete(); | |
}); | |
} | |
public function validate() | |
{ | |
// ... Your validation goes here ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment