You know that in Laravel we can delete records with foreign keys by creating on delete cascade features. Laravel 9 releases a new feature called noActionOnDelete. This noActionOnDelete helps you to generate your foreign key constraint but it can not delete your relational data like on delete cascade.
Yes, now Laravel has a foreign key without a constraint. We can now define laravel foreign key constraints without cascade. Look at that, the below example is with cascade with foreign key constraints.
The example of laravel delete record with foreign key:
<?php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(User::class)
->constrained()
->cascadeOnUpdate()
->cascadeOnDelete();
$table->mediumText('title')->unique();
$table->integer('post_views')->default(0);
$table->boolean('is_published')->default(true);
$table->timestamps();
});
}
Now see the example of noActionOnDelete in Laravel:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table
->foreign('user_id')
->references('id')
->on('users')
->noActionOnDelete();
$table->mediumText('title')->unique();
$table->integer('post_views')->default(0);
$table->boolean('is_published')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
Read also: Read CSV File And Database Seeder Example In Laravel
Conclusion
I have tried to discuss the clear concept of can you have a foreign key without a constraint. Now we know laravel foreign key constraint without cascade. Hope this noActionOnDelete Laravel tutorial will help you.