How to name a pivot table in many-to-many in Laravel

The default naming convention of Laravel many-to-many pivot table is xxxxx_yyyyy, where "xxxxx" and "yyyyy" are names of related tables, in singular form, in alphabetical order.

Example: pivot table between users and locations should be called location_user.

The wrong names would be location_users (because it's not singular) or user_location (because "user" and "location" is not in alphabetical order).

If you follow those naming conventions, you can define the belongsToMany relation without extra parameters:

app/Models/User.php

public function locations()
{
return $this->belongsToMany(Location::class);
}

If you name this table differently, you need to pass its name as a second parameter:

public function locations()
{
return $this->belongsToMany(Location::class, 'users_locations');
}
avatar

Why the following does not work?

Table 1: businesses

Table 2: business_tags

Pivot Table: business_business_tag

avatar

Probably Laravel misinterprets some repeating word differenly, not sure.

You can specify that table as the second parameter in your pivot function in the Model.

Or, if I were you, I would rename tables differently, it's quite confusing.

Like our articles?

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

Recent Premium Tutorials