How to create table with foreign keys in laravel?

Member

by addison , in category: PHP Frameworks , 5 months ago

How to create table with foreign keys in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 5 months ago

@addison 

To create a table with foreign keys in Laravel, you can use the Schema facade provided by Laravel's database migration feature. Here's an example of how you can create a table with foreign keys in a migration file:

  1. Create a migration file using the php artisan make:migration command:
1
php artisan make:migration create_posts_table


  1. Open the generated migration file (located in the database/migrations directory) and define the schema for your table with foreign keys. You can use the foreign method to specify the foreign key constraints. Here's an example of creating a posts table with a foreign key referencing the user_id column of the users table:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}


  1. Run the migration to create the table in your database:
1
php artisan migrate


This will create a posts table with a foreign key constraint on the user_id column referencing the id column of the users table.