Alberto
Alberto

Reputation: 12909

How to fetch only a specified field from pivot with "with" function

I'm using Laravel 6.0 anc i can't figure out how to fetch just a specified field from the pivot table with the with eager loading.

For the relationships i use

$builder->with('relation_name:field1,field2")

But it doesn't work for the pivot of that relation. Is there any way to do it or have i got to unset the others fields manually?

Upvotes: 0

Views: 45

Answers (1)

Watercayman
Watercayman

Reputation: 8178

For relations, the withPivot() method on the relationship is probably what you are looking for:

 $builder->with(['relation_name' => function ($query) {
      $query->withPivot('field1')->withPivot('field2');
 }])->get();

You can combine, but for clarity, this is simplest.

Upvotes: 1

Related Questions