I need to find a group of collection WHERE the search is based on a record on a related model. To let you understand I need to get users with the company name that is LIKE my search input.
Here's what i've tried:
$users = App\User::with(['company' => function ($query) {
$query->where('company_name', 'like', '%'.$searchInput.'%');
}])->paginate(10);
To be honest I spent hours on this but with no luck. I'm using jenseggers/mongodb
on laravel 5.8.
You should add ::whereHas()
to your query which will limit query results where company
is like the search query.
Also you will need to change the ::with()
closure to ::with('companies')
.
$users = App\User::whereHas('company', function ($query) use ($searchInput) {
$query->where('company_name', 'like', '%'.$searchInput.'%');
})
->with('company')
->paginate(10);
Note the use ($searchInput)
.
Also check if the user relation is companies
instead of company
.