Does anyone have any suggestions for how to use makeHidden()
when eager-loading? here is my code:
$work=Work::with([
'work_category'=>function($query){
$query->with(['companies'=>function($query){
$query->select('companies.id','companies.name');
}]);
},
'prices',
])
->findOrFail($id);
Work has a belongsTo('App\WorkCategory')
relationship, and WorkCategory has a belongsToMany('App\Company')
relationship through a pivot.
If I try to chain ->makeHidden('pivot')
on to $query->select('companies.id','companies.name');
- I get a BadMethodCall exception: Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::makeHidden()
Is there something I'm missing here?
This is the code with the offending makeHidden() call
$work=Work::with([
'work_category'=>function($query){
$query->with(['companies'=>function($query){
$query->select('companies.id','companies.name')->makeHidden('pivot');
}]);
},
'prices',
])
->findOrFail($id);
My temporary fix has been to add protected $hidden=['pivot'];
to my Company model, however it would be nice to be able to access the pivot when I do need it, and use $model->relation->makeHidden('attribute')
in my controllers to trim away extra data before sending.
Unfortunately, makeHidden()
doesn't work on relationships in Laravel. Not directly nor using dot notation on the related field.
You've touched upon one solution that I've used in the past, which is to use select()
to limit to only the relationship's fields that you want within the subquery as a somewhat rough way to exclude your pivot:
$query->with(['companies'=>function($query){
$query->select('id','name', 'something', 'something');
}]);
This works when the fields are limited. But its a pain when you have a lot or are making many queries.
Another alternative is to do what you've done, and mark it protected on the model: protected $hidden=['pivot'];
. You then have some flexibility in various methods to use ->makeVisible('pivot');
on the fly to regain access to this pivot.