Laravel Basic
Laravel Form
Laravel Database
Laravel Advance
public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('users'); }
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:
Name | Type |
---|---|
id | bigint(20) |
name | varchar(255) |
created_at | timestamp |
updated_at | timestamp |
Name | Type |
---|---|
id | bigint(20) |
images | varchar(255) |
user_id | bigint(20) |
created_at | timestamp |
updated_at | timestamp |
Laravel makes relationships easy:
$table->foreignId('user_id')->constrained();
(OR)
$table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users');
$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');
$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');