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.

Leave a Comment