laravel migration foreign key example
Example 1: laravel foreign key
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
OR
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
Example 2: laravel migration add unique column
Schema::table('tableName', function($table)
{
$table->string('column-name')->unique(); //notice the parenthesis I added
});
Example 3: foreign key laravel migration
$table->foreign('column_name')->references('id')->on('table_name')->onDelete('cascade');
Example 4: create foreign key laravel migration
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Example 5: laravel 8 foreign key migration
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Example 6: laravel migration drop foreign keys
$table->dropPrimary('users_id_primary');