Search code examples
laraveleloquenteloquent-relationship

How to delete a user in Laravel (eloquent) without its relations?


I have a laravel application and I want to delete the user record form users table but keep the data related to them like articles.

I have this function for article

public function userArticles()
    {
        return $this->hasMany('Application\Model\userArticles');
    }

I want to delete the user without deleting the articles from database, but when I do $user->delete() it deletes everything.

is there a way to keep the articles?


Solution

  • UPDATE YOUR MIGRATION ->onDelete('set null') It means when the user was deleted, the field will be null.

    $table-> bigInteger('user_id')->unsigned()->nullable()->index();
    $table->foreign('user_id')->references('id')->on('admins')->onDelete('set null');