Creating Foreign Key References in Laravel Migration


How to Add Foreign Key References in Laravel Migration


Laravel really par at facilitating data integrity management and navigation of table relations, but you'll need to understand how to properly configure these relationships before taking advantage of them.

Consider a Fleet example application's relationship between a Vehicle and assigned Brand. Each vehicle belongs to a Brand, whereas each brand can have many vehicles. This means the vehicles table will contain a foreign key named brand_id (although it is possible to override the foreign key field name if you desire). In this tutorial I'll show you the steps necessary to configure this has many /belongs to relationship using migrations and model relations.

Let's start off by creating the migration:

$ php artisan make:migration add_brand_id_to_vehicles --table=vehicles

You're free to name the migration anything you wish; I try to be as explicit as possible so as to easily find the migration later should it require further modification. After executing this migration you'll find a file named 2018_01_28_145776_add_brand_id_to_vehicles.php (the timestamp prefix will of course be different) in your project's database/migrations directory. Open this file and you'll find the usual up() and down() methods. Modify the up() method to look like this:

public function up()
{
    Schema::table('vehicles', function(Blueprint $table)
    {
        $table->integer('brand_id')->unsigned()->after('id');
        $table->foreign('brand_id','fk_vehicle_brand_id')->references('id')->on('vehicle_brands')->onUpdate('CASCADE')->onDelete('CASCADE');
    });
}

Only two lines comprise the up() method, yet both are probably rather confusing to the newcomer. The first line creates an column named brand_id of type integer (unsigned), placing it directly after the id column. You don't have to be bothered with placing the column in a specific location; I just like to place my primary key and foreign keys at the "top" of the table.

The second line identifies this newly created column as being a foreign key, and specifies that it refers to the vehicle_brands table's id column.

That wasn't so bad, was it? Next up is the down() method:

public function down()
{
    Schema::table('vehicles', function(Blueprint $table)
    {
        $table->dropForeign('fk_vehicle_brand_id');
        $table->dropColumn('brand_id');
    });
}

These two lines aren't perhaps so confusing ; should we need to roll back the migration, the foreign key reference and column itself will be removed (dropped).

After saving the changes, run the migration as usual:

$ php artisan migrate
Migrated: 2018_01_28_145776_add_brand_id_to_vehicles.php

With the table schema updated, you'll next need to update the Brand and Vehicle model. Starting with Brand.php, add the following method:

public function vehicles()
{
    return $this->hasMany('App\Vehicles');
}

Save the changes, and open up the Vehicle model (Vehicle.php), adding the following method:

public function brand()
{
    return $this->belongsTo('App\Brand');
}

With these changes in place you're ready to begin using your new relation

If you have any other questions, experience or insights on "Adding Foreign Key References Using Laravel Migration" please feel free to leave your thoughts in the comments bellow which might be helpful to someone some day!

Written by Akram Wahid 6 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}