Eloquent relationship with different table name and table fields for belongsToMany using pivot table?


Posted 2 weeks ago | by Ryan Dhungel | on Eloquent Laravel  | Viewed 88 times

Solution to belongsToMany relationship with pivot table that has different naming to their table name and column fields.

The standard way:

This example would work if you have named your database table and column fields appropiratelyThis is how it shuold look like inside Product.php

The standard way is alway use singular version of the model name, follow the alphabetical order and use underscore

public function categories()
{
// We have already created pivot table for products and categories
return $this->belongsToMany(Category::class);
}

You have changed your table name

This is how you have to supply table name if you have used different table name

public function categories()
{
return $this->belongsToMany(Category::class, 'products_categories');
}

You have changed your table fields names too

This is how you have to supply table name along with column fields name if you have used different naming convention
The right way would be naming fields as category_id and product_id

public function categories()
{
/** * The order here is Table name comes first then comes local name and foreign name * Table name 'products_categories' * Local name 'prod_id' * Foreign name 'cate_id' */
return $this->belongsToMany(Category::class, 'products_categories', 'prod_id', 'cate_id');
}


Specials


Build Laravel React CRUD/SPA APP in 2 hours
Build Laravel React CRUD/SPA APP in 2 hours

Build Laravel React CRUD/SPA APP in 2 hours

COUPON CODE: REACTCRUD with 90% off


Laravel with React JS - Build Twitter Like Real Ti...
Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

COUPON CODE: LARAVELREACT with 90% off


Learn Laravel Building Multi User Blogging Platfor...
Learn Laravel Building Multi User Blogging Platform with SEO


React Redux Firebase CRUD App with Authentication
React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

COUPON CODE: RRFTEN with 86% off


Become a Master of JavaScript from Scratch in 2018
Become a Master of JavaScript from Scratch in 2018

Become a Master of JavaScript from Scratch in 2018

COUPON CODE: JSMASTERSALE with 92% off


REACT - Up and Running with React ES6 and Open Sou...
REACT - Up and Running with React ES6 and Open Source API


Sublime Text for Rapid Web Development
Sublime Text for Rapid Web Development

Sublime Text for Rapid Web Development

COUPON CODE: LEARNSUBLIME with 90% off