How is a pivot table created by Laravel? How is a pivot table created by Laravel? laravel laravel

How is a pivot table created by Laravel?


It appears as though the pivot table does need to be created manually (i.e. Laravel does not do this automatically). Here's how to do it:

1.) Create a new migration, using singular table names in alphabetical order (default):

php artisan make:migration create_alpha_beta_table --create --table=alpha_beta

2.) Inside the newly created migration, change the up function to:

public function up(){    Schema::create('alpha_beta', function(Blueprint $table)    {        $table->increments('id');        $table->integer('alpha_id');        $table->integer('beta_id');    });}

3.) Add the foreign key constraints, if desired.(I haven't gotten to that bit, yet).


Now to seed, say, the alpha table, using keys from beta, you can do the following in your AlphaTableSeeder:

public function run(){    DB::table('alpha')->delete();    Alpha::create( array(         'all'           =>  'all',        'your'          =>  'your',        'stuff'         =>  'stuff',    ) )->beta()->attach( $idOfYourBeta );}


I use Jeffrey Way's Laravel-4-Generators or Laravel-5-Generators-Extended.

then you can just use this artisan command:

php artisan generate:pivot table_one table_two


To expand on Ben's answer (I tried to edit it but reviewers said it added too much):

To add the foreign key constraints, make sure if alpha id is unsigned, alpha_id is also unsigned in the pivot table. This migration would run after (2) in Ben's answer since it alters the table created then.

public function up(){    Schema::table('alpha_beta', function(Blueprint $table)    {        $table->foreign('alpha_id')->references('id')->on('alpha');        $table->foreign('beta_id')->references('id')->on('beta');    });}