Belongs to Many Pivot table naming

To determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order.

This would mean a join between Post and Tag could be added like this:

1class Post extends Model
2{
3 public $table = 'posts';
4 
5 public function tags()
6 {
7 return $this->belongsToMany(Tag::class);
8 }
9}

However, you are free to override this convention, and you would need to specify the join table in the second argument.

1class Post extends Model
2{
3 public $table = 'posts';
4 
5 public function tags()
6 {
7 return $this->belongsToMany(Tag::class, 'posts_tags');
8 }
9}

If you wish to be explicit about the primary keys you can also supply these as third and fourth arguments.

1class Post extends Model
2{
3 public $table = 'posts';
4 
5 public function tags()
6 {
7 return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
8 }
9}

Tip given by @iammikek

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord