I have a model with relations, and need to filter this relations depending on request parameter.
On controller I get all properties with his owners (a property can have several owners, and vice versa).
Property controller:
$property= Property::query()
->when($request->search, function($query, $search) {
$query->where('name','like', '%'.$search.'%')
->orWhere('name2','like', '%'.$search.'%')
->orWhere('city','like', '%'.$search.'%');
})
->select(['id', 'name', 'published'])
->with(['photo', 'owner', 'destiny'])->get();
And in property model:
public function owner(){
return $this->belongsToMany(
Owner::class,
'rel_owners_properties'
)->select(['owner.id', 'owner.nombre', 'owner.nombre_empresa']);
}
Now, if I have a $request->ownerId value in controller, I need to filter only the properties that this owner has.
I have tried with something like this, but I receive all the properties without any owner:
$property= Property::query()
->when($request->search, function($query, $search) {
$query->where('name','like', '%'.$search.'%')
->orWhere('name2','like', '%'.$search.'%')
->orWhere('city','like', '%'.$search.'%');
})
->select(['id', 'name', 'published'])
->with([
'photo',
'owner' => function ($query) use ($request) {
$query->where(['owner_id' => $request->ownerId]);
},
'destiny'
])->get();
CodePudding user response:
To filter by a relationship you need to use whereHas
:
$property = Property::query()
->when($request->search, function ($query, $search) {
$query->where('name', 'like', '%' . $search . '%')
->orWhere('name2', 'like', '%' . $search . '%')
->orWhere('city', 'like', '%' . $search . '%');
})
->select(['id', 'name', 'published'])
->whereHas('owner', function ($query) use ($request) {
$query->where('id', $request->ownerId);
});
->with([
'photo',
'owner'
'destiny'
])->get();