nscode
nscode

Reputation: 157

Keep User comment on comment delete Laravel

I want to create a comment sections for my articles. My logic says that Article has many comments and User(reader of the articles) has many comments. So I made a table with 2 foreign keys.

If the article is deleted -> cascade and delete the comments.

How do I make that if user is deleted, I keep the comment on the article? here is the code:

        Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->text('body');
        $table->unsignedBigInteger('article_id');
        $table->unsignedBigInteger('user_id');
        $table->timestamps();

        $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('**what do I write here?**');
    });

Upvotes: 0

Views: 191

Answers (2)

Aditya Taruna
Aditya Taruna

Reputation: 1

Just simply add SoftDeletes on your model

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

https://laravel.com/docs/5.7/eloquent#soft-deleting

Upvotes: 0

Robert Kujawa
Robert Kujawa

Reputation: 997

You must set the 'user_id' column to nullable, so that when you delete a user from you database you can set that to null.

$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');

Then in your front end you can do:

$comment->user()->exists() ? $comment->user->username : 'Unknown User';

Upvotes: 5

Related Questions