Home > Mobile >  Laravel search and display only the selected id
Laravel search and display only the selected id

Time:06-12

I have a page that must only shows some specific rows from the database table and on that page there is a search form.

$benefiteds = Beneficiary::whereIn('id', $ids)->paginate(30);

return view('pages.program_show', compact('benefiteds'), $userData)->with('program', $program);

My search query:

$benefiteds = Beneficiary::whereIn('id', $ids)
->where('last_name', 'LIKE', '%'.$request->search.'%')
->orWhere('first_name', 'LIKE', '%'.$request->search.'%')
->orWhere('middle_name', 'LIKE', '%'.$request->search.'%')
->paginate(30);

The problem here is whenever i try to search, the whereIn function doesn't work and it also returns some rows that it is not part on the query. Is there another way to achieve these?

Click here to see image:

Only the id of the second row is part of array ids the first and third row isn't

The returned first and third row's id doesn't exist on the array ids, only the id of the second row exist in the array ids

CodePudding user response:

You will need to use logical grouping

$benefiteds = Beneficiary::whereIn('id', $ids)
    ->where(function($query) use($request) {
        $query->where('last_name', 'LIKE', '%'.$request->search.'%')
            ->orWhere('first_name', 'LIKE', '%'.$request->search.'%')
            ->orWhere('middle_name', 'LIKE', '%'.$request->search.'%')
    })
    ->paginate(30);

Laravel Docs - Queries - Logical Grouping

  • Related