PASSWORD RESET

Your destination for complete Tech news

How to set a column null on delete in Laravel?

1.73K 0
< 1 min read

To set a column to NULL on delete in Laravel, you can use the onDelete method in your migration file.

For example, suppose you have a posts table with a user_id column that is a foreign key to the id column in a users table. To set the user_id column to NULL when a user is deleted, you can use the following migration:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddForeignKeysToPostsTable extends Migration
{
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
        });
    }

    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });
    }
}

This will add a foreign key constraint to the user_id column with a set null on delete action. This means that when a user is deleted, any rows in the posts table with a user_id matching the deleted user’s id will have the user_id column set to NULL.

You can then run the migration using the php artisan migrate command.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.