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.
