Laravel relationships in migrations? Laravel relationships in migrations? laravel laravel

Laravel relationships in migrations?


When creating a migration you can specify foreign keys on your tables,i.e.

public function up(){    Schema::table('roles', function(Blueprint $table) {        $table->increments('id');        $table->integer('user_id')->unsigned();        //rest of fields then...        $table->foreign('user_id')->references('id')->on('users');    });}

This will create a foreign key on the user_id column on the roles table.The benefits of foreign keys is that when an update or delete is made the foreign key table will be automatically updated or "cascaded" great description found here

As described on the Laravel documentation you could also specify your cascading on update using the following syntax

$table->foreign('user_id')  ->references('id')->on('users')  ->onDelete('cascade');

I would do a bad job of trying to explain it better than the documentation does so please have a read through the "Relationships" section of the Eloquent ORM documentation to see how its done.


It looks like a few of the initial questions were never answered, i.e. "When, and how is the relationship table created" & "will the middle table be created automatically":

As far as I am aware, these tables need to be created manually. So create the migration file like so:

Laravel 5

php artisan make:migration create_role_user_table

Laravel 4

php artisan migrate:make create_role_user_table

Note that the names are singular, and are presented in alphabetical order.

Then in the migration something like:

public function up(){    Schema::create('role_user', function($table) {        $table->increments('id');        $table->integer('role_id');        $table->integer('user_id');        $table->timestamps();    });}

Hope that helps. I'm not sure if the timestamps are needed in Pivot Tables or not, so please experiment.


Though its an old Post, I though I can contribute something updated. For Laravel5, Jeffrey Way has developed a package Laravel5 Generators-extended which enhance the generator capability of php artisan for

  • make:migration:schema
  • make:migration:pivot
  • make:seed

For many-to-many relation between users and role, you can just use

php artisan make:migration:pivot users role

and it will generate the required migration class. You don't need to code manually for this.