1

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.

Rahul
  • 18,271
  • 7
  • 41
  • 60
McMazalf
  • 59
  • 1
  • 9

1 Answers1

1

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.

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17