Tucker-Eric / EloquentFilter

An Eloquent Way To Filter Laravel Models And Their Relationships
http://tucker-eric.github.io/EloquentFilter
MIT License
1.72k stars 120 forks source link

Applying filter to a relationship collection #117

Closed devchalkie closed 4 years ago

devchalkie commented 4 years ago

Hi, I have User model which has relationship say books(), i want to do something like $user->books->filter($request->all()) so that user can only filter through his books.

Any suggestion please.

Thanks, Hussain

Tucker-Eric commented 4 years ago

Yup, you can do that if you switch to calling books as a method so you still have access to the related query before it's executed.

This should do the trick:

$user->books()->filter($request->all())->get();
devchalkie commented 4 years ago

Thank you a lot, that makes it a lot easier :) awesome work. 👍

anon38575347537 commented 4 years ago

Don't work for me

anon38575347537 commented 4 years ago

$searches = $user->searches()->filter($request->all())->get();

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::filter()

benrolfe commented 3 years ago

@bitdev1999 I have the same issue. Any suggestions @Tucker-Eric?

Tucker-Eric commented 3 years ago

@benrolfe In that case he relation needs to use the Filterable trait. So the model that searches returns in the relationship needs to implement that Filterable trait.