Adding foreign keys to Laravel’s migrations and schema builder

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->string('name', 150);

Schema::table('pets', function($table) {
    $table->string('name', 50);

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