Skip to content

Instantly share code, notes, and snippets.

@fredyounan
Last active July 20, 2019 11:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fredyounan/8328483 to your computer and use it in GitHub Desktop.
Save fredyounan/8328483 to your computer and use it in GitHub Desktop.
Eloquent boot method
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