在Laravel中的where,whereHas执行查询

I'm building a small application in Laravel 5.5 where I'm querying something like this:

$models = Contact::where('first_name', 'LIKE', '%'.$request->search_input.'%')
    ->orWhere('last_name', 'LIKE', '%'. $request->search_input.'%')
    ->orWhereHas('company', function ($q) use($request) {
        $q->where('name', 'LIKE', '%'.$request->search_input.'%');
    })
    ->whereHas('company', function ($query) {
        $query->where('type', '=', 'Research');
    })
    ->orderBy('created_at', 'desc')
    ->take(50)
    ->get();

The idea behind is, I want to search the list of contact with first_name, last_name and their company name (which is a relational data) with the search_input and filter them with type = Research in the company list, I mean only those contact should appear which is having company type as research.

But currently I'm getting all the list of contacts without filtering it with type. Help me out with this. Thanks.

You need to use where closure:

Contact::where(function($q) use($request) {
        $q->where('first_name', 'like', '%' . $request->search_input . '%')
          ->orWhere('last_name', 'like', '%' . $request->search_input . '%')
          ->orWhereHas('company', function ($q) use($request) {
              $q->where('name', 'like', '%' . $request->search_input . '%');
        });
    })
    ->whereHas('company', function ($query) {
        $query->where('type', 'Research');
    })
    ->latest()
    ->take(50)
    ->get();