how to use foreign key in laravel 5.1 migration

At last generate a migration for the table keep in mind that they should be in order if you feel any diffuculties just name ur table_foreign_keys

 Schema::table('samples', function($table) {
            $table->foreign('supplier_id')->references('id')->on('suppliers');
            $table->foreign('unit_id')->references('id')->on('unit');
            $table->foreign('category_id')->references('id')->on('category');
        });

place all foreign keys related here at last and run


Order matters.

You want to be sure that your "suppliers" table exists before attempting to reference a column on that table as a constraint.

So If you want to set your foreign key Constraint while creating your table then make sure that you create the "suppliers" migration first, and the "samples" migration afterwards:

php artisan make:migration create_suppliers_table --create=suppliers
php artisan make:migration create_samples_table --create=samples

...add schema code to your migration files. and then:

php artisan migrate

If you don't want to worry about the order in which the tables are created then do your create_table migrations first, without the foreign key constraints, and then do an additional migration to add your foreign keys.

php artisan make:migration create_samples_table --create=samples
php artisan make:migration create_suppliers_table --create=suppliers
php artisan make:migration alter_samples_table --table=samples   <-- add your foreign key constraints to this migration file

...add schema code to your migration files. And then migrate using:

php artisan migrate