Advertisement
Google Ad Slot: content-top
Laravel Foreign Key Table
Foreignkey
users migration
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
profiles migration
public function up(): void
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('image');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
});
}
public function down(): void
{
Schema::table('profiles', function (Blueprint $table) {
$table->dropForeign(['user_id']); // Drop Foreign Key first
});
Schema::dropIfExists('profiles');
}
If you drop the profiles table, Laravel will handle dropping the foreign key automatically. But in some MySQL versions, it may throw an error. To be safe, you can explicitly drop the foreign key before dropping the table:
Output:
users table
| Name | Type |
|---|---|
| id | bigint(20) |
| name | varchar(255) |
| created_at | timestamp |
| updated_at | timestamp |
profiles table
| Name | Type |
|---|---|
| id | bigint(20) |
| images | varchar(255) |
| user_id | bigint(20) |
| created_at | timestamp |
| updated_at | timestamp |
Foreign Key Constraints
Laravel makes relationships easy:
$table->foreignId('user_id')->constrained();
(OR)
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
Add onDelete / onUpdate behavior:
$table->foreignId('user_id')
->constrained()
->onDelete('cascade')
->onUpdate('cascade');
(OR)
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
Set Foreign Key to NULL on Delete
$table->foreignId('user_id')
->nullable()
->constrained()
->nullOnDelete(); // shorthand for onDelete('set null')
(OR)
$table->unsignedBigInteger('user_id')->nullable(); // must be nullable
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('set null');