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

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

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

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Recent Premium Tutorials