Extra Field with Extra Relationship in Laravel Pivot Table Example

Hello artisan,

In this laravel pivot table tips tutorial, I will discuss some tips with you. You know that laravel many to many relationship brings pivot table. We also know that we need a pivot table with many to many relationship. But sometimes Iin many-to-many relationships, your pivot table may contain extra fields, and even extra relationships to other Model.

How do you handle that situation? I am here to show you that tips that how i handle this situation with extra relationship with pivot table. Fo that we need to generate a separate pivot table, Let's see the example code.

Let assume we have a RoleUser model like that:

php artisan make:model RoleUser --pivot

 

Now if you see the RoleUser model, notice extends Pivot, not Model

app\Models\RoleUser.php

use Illuminate\Database\Eloquent\Relations\Pivot;

class RoleUser extends Pivot
{
	public function team()
	{
	    return $this->belongsTo(Team::class);
	}
}

 

Now we have to take advantage of it. So next, specify it in belongsToMany() with ->using() method. Then you could do magic, like in the example.

app/Models/User.php


public function roles()
{
	return $this->belongsToMany(Role::class)
	    ->using(RoleUser::class)
	    ->withPivot(['team_id']);
}

 

Now we can do to fetch data like that:

$user->roles()->first()->pivot->team->name

 

Read also: How to Fetch Todays Records From Database In Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js