How is a pivot table created by Laravel?

Ben picture Ben · Apr 4, 2013 · Viewed 49.8k times · Source

In Laravel 4, when working with many-to-many relationships as described in the 4.2 docs, how can I actually get Laravel to create the pivot table for me?

Do I need to add something in my migrations for the two models that are involved? Do I need to manually create a migration for the pivot table? Or how does Laravel know to create the pivot table?

All I've done so far is add the belongsToMany information to the two respective models, i.e.

class User extends Eloquent 
{
    public function roles()
    {
         return $this->belongsToMany('Role');
     }
 }

However, that does not trigger creation of the pivot table. What step am I missing?

Answer

Ben picture Ben · Apr 5, 2013

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 );
}