Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Get pivot data for specific many to many relation

My User model has many Target and vice versa. Now I've got a given User and given Target and I want to access pivot data from their relation. The pivot column is called type

How can I achieve this?

like image 387
Bernd Strehl Avatar asked Dec 11 '14 23:12

Bernd Strehl


People also ask

How do I get pivot table data in Laravel?

On the relationships for both User and Target , tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type .

How do you access data from a pivot table?

Follow these steps, to find the data source of a pivot table: Select any cell in the pivot table. On the Ribbon, under the PivotTable Tools tab, click the Analyze tab (in Excel 2010, click the Options tab). In the Data group, click the top section of the Change Data Source command.

What is pivot table in Laravel 8?

The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.


1 Answers

On the relationships for both User and Target, tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type.

If you're not iterating over a collection, but have a user and one of their targets and want the type field, you could use $target = $user->targets->find($targetId) and access the type with $target->pivot->type.

More at http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

like image 148
maknz Avatar answered Sep 19 '22 16:09

maknz