Skip to main content
Tutorial Free

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

January 22, 2023
1 min read

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');
}

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

Pablo avatar

Why the following does not work?

Table 1: businesses

Table 2: business_tags

Pivot Table: business_business_tag

Povilas Korop 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.

👍 1
Chris De David avatar

@Pablo It's because Laravel sucks when it comes to tables with 2 words in them. I struggled with this for a long time. Who knows what the magic does behind the scenes, while the documentation never has a 2 word table name, like they don't friggen exist!

Do laravel devs join the words?? Do they just name their table "businesstags"??

What I end up doing is minimizing the magic, and just specifying the table names in all relationships (belongsTo etc.), and at the top of all my model classes $table = "..."

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.