Prevent deletion of parent if it has child records
Let's say we have model User and Comment. I want to prevent deletion user if he has comments. To do so we need to look at model events at laravel's doc
Example
class User extends Eloquent
{
public function comments()
{
return $this->has_many('Comment');
}
protected static function boot() {
parent::boot();
static::deleting(function($user) {
if ($user->comments()->count() > 0)
{
throw new Exception("Model have child records");
}
});
}
}
P.S. english is not my native language
Written by Adis
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Laravel
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#