Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Pivot Table with Extra Columns in Laravel


To get data from pivot table:

By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

return $this->belongsToMany('App\Models\Role')->withPivot('column1', 'column2');


$price = $model->problems()->findOrFail($problem->id, ['phone_problem'])->pivot->price;


Or if you have many records with different price:

$price = $model->problems()->where('phone_problem', $problem->id)->firstOrFail()->pivot->price;


To update data in the pivot you can go NEW WAY:

$model->problems()->sync([$problemId => [ 'price' => $newPrice] ], false); 

Where the 2nd param is set to false meaning that you don't detach all the other related models.

Or, go old way

$model->problems()->updateExistingPivot($problemId, ['price' => $newPrice]);


To delete:



To create new:

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:


$user->roles()->attach($roleId, ['expires' => $expires]);
$model->problems()->attach($problemId, ['price' => 22]);


For convenience, attach and detach also accept arrays of IDs as input:

$user = App\Models\User::find(1);

$user->roles()->detach([1, 2, 3]);

    1 => ['expires' => $expires],
    2 => ['expires' => $expires],


Example with sync method:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);


Example with save method:

When working with a many-to-many relationship, the save method accepts an array of additional intermediate table attributes as its second argument:

App\Models\User::find(1)->roles()->save($role, ['expires' => $expires]);


Example with update method:

$user = App\Models\User::find(1);

$user->roles()->updateExistingPivot($roleId, ['price' => $price]);


Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon