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

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

The standard way is alway use singular version of the model name, follow the laravel naming convensions. here we are giving a example, article written by multiple authors who has registered, we will add belongsToMany relationship to authors with pivot table.


// Article Model

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

Changed your table name

you have to supply table name if you have used different table name as below:


// Article Model

public function authors()
{
	// We have already created pivot table for articles and authors
	return $this->belongsToMany(User::class, 'article_author');
}

Changed your table fields name too

The right way would be naming fields as article_id and user_id // we have User model that contain author details you have to supply table name along with column name if you have used different naming convention


// Article Model

public function authors()
{
	// We have already created pivot table for articles and authors
	return $this->belongsToMany(User::class, 'article_author', 'art_id', 'author_id');
}

Hope this helps you...

Please put comments below if you wants to add more suggestions about it.

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone