Skip to content

Pivot Tables

Vladimir Schneider edited this page Oct 26, 2015 · 2 revisions

Creating joinable/pivot tables can sometimes be confusing.

  • Should the table names be plural?
  • In what order do we write the table names to make Laravel happy?
  • What fields should be in the pivot table?

This process can be automated now. Simply call the generate:pivot command, and provide the names of the tables that should be joinable. For example, a post can have many tags, and a tag can have many posts. Run the following command to create the necessary pivot table.

php artisan generate:pivot posts tags

It doesn't matter which order you provide the table names (or whether you pluralize them or not). The command will correctly create a post_tag migration that has post_id and tag_id fields.

Schema::create('post_tag', function(Blueprint $table) {
    $table->integer('post_id');
    $table->integer('tag_id');
});

Finally, simply migrate the database to create it.

php artisan migrate

Pivot table finished!

To put it all together, let's do it from scratch. We need a posts table, a tags table, and the connecting pivot table for the two. We can tackle this easily with the generators.

php artisan generate:migration create_posts_table --fields="title:string, description:text"

php artisan generate:migration create_tags_table --fields="name:string"

php artisan generate:pivot posts tags
Clone this wiki locally