Search code examples
laravelrelationships

laravel relationship one to many


before anything ,Highly appreciated in advance for help . i have two model user:

public function posts(){
return $this->hasMany('App\Post');}

post:

public function user(){
return $this->belongsTo('App\user');}

my post have column "user_id" so every post have owner "user_id".

here is my question: i want to delete user but nothing happen to related post. right now i can do this ,but my problem is post_id column have id belongs to deleted user. i want to change that to "null" or "0".


Solution

  • You can do this with model events. Something like this on your User model.

    public static function boot() {
      parent::boot();
    
      static::deleting(function($user) {
        $user->posts()->update(['user_id' => null]);
      });
    }
    

    Also make sure the user_id field is nullable on the migration.