Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EsO's avatar
Level 1

Laravel advance search query

Hey guys, need some more advice again. Trying to create a search function in my app.

Currently, I have the search working that it matches the search query against a model and its relationships design bringing up records that have that text in the columns.

But I want the search to work also where the search query is design photography where it brings up records matching both terms individually or together.

Currently, it brings up nothing.

Here is my current code

              $opps->with(['opportunity_type', 'employment_type', 'sector', 'employer', 'employer.user'])->where(
                function ($query) use ( $request) {

                  // Grab records that have the 'query' matched in the title/description
                  $query->where('title', 'LIKE', "%{$request->input('query')}%")
                  ->orWhere('description', 'LIKE', "%{$request->input('query')}%");
                })
              ->orWhereHas('opportunity_type', $filter = function ($query) use ($request) {
                  foreach (explode(' ', $request->input('query')) as $searchTerm) {

                    // Grab records where the opportunity type relationship 'type' matches the 'query'
                    $query->where('type', 'like', "%{$searchTerm}%");
                  }

              })->orWhereHas('employment_type', $filter = function ($query) use ($request) {
                  foreach (explode(' ', $request->input('query')) as $searchTerm) {

                    // Grab records where the employment type relationship 'type' matches the 'query'
                    $query->where('type', 'like', "%{$searchTerm}%");
                  }

              })->orWhereHas('sector', $filter = function ($query) use ($request) {
                  foreach (explode(' ', $request->input('query')) as $searchTerm) {

                    // Grab records where the sector relationship 'name' matches the 'query'
                    $query->where('name', 'like', "%{$searchTerm}%");
                  }

              })->orderBy("updated_at");```
0 likes
1 reply
jlrdw's avatar

Have two search inputs like: https://drive.google.com/file/d/0B1_PFw--3o74YjVreHNBOWU2aEE/view

And you need to get search parameters into variables, and I did this:

        $query = Dog::where('dogname', 'like', $dogsch);
        if ($aval == "n") {
            $query->where('adopted', '=', 1);
        } else if ($aval == "y") {
            $query->where('adopted', '=', 0);
        }
        $dogs = $query->orderBy('lastedit', 'DESC')->paginate(5);

pass the appends array along also:

$pagelinks = array('psch' => $dogsearch, 'aval' => $aval);

SO view

$dogs->appends($pagelinks)->links();

Please or to participate in this conversation.