Last Updated: February 25, 2016
· across

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


class User extends Eloquent
    public function comments()
        return $this->has_many('Comment');

    protected static function 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