Adding foreign keys to Laravel’s migrations and schema builder

By | April 22, 2013

At work, there was an issue with using Laravel’s migrations and the scheme builder with tables that needed foreign keys. It’s not in the official documents, but after some source code searching, there is a solution that works well…

For example, you have a Users table and each User has Pets (one-to-many). If the User is deleted from the database, you want all their Pets to be deleted as well. In our up method in the migration, we would do something like this:

Schema::table('users', function($table) {
    $table->increments('id')->unsigned();
    $table->string('email');
    $table->string('name', 150);
    $table->timestamps();
});

Schema::table('pets', function($table) {
    $table->increments('id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->string('name', 50);
    $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
});

edit: cascade, not cascase. (ht David Stanley)