Only until Jan 16th: coupon RESOLUTION25 for 40% off Yearly/Lifetime membership!

Read more here

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:

class Post extends Model
{
public $table = 'posts';
 
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}

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

class Post extends Model
{
public $table = 'posts';
 
public function tags()
{
return $this->belongsToMany(Tag::class, 'posts_tags');
}
}

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

class Post extends Model
{
public $table = 'posts';
 
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
}

Tip given by @iammikek

Like our articles?

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

Recent New Courses