skip to Main Content

I have a search on the title, description and author fields, is there a way to make it faster or shorten the code?

    public function index(Request $request)
    {
        $queryStr = $request->query('search');

        $games = Game::withTrashed()
            ->with('user')
            ->where('title', 'like', '%' . $queryStr . '%')
            ->orWhere('description', 'like', '%' . $queryStr . '%')
            ->orWhereHas('user', function ($query) use ($queryStr) {
                $query->where('username', 'like', '%' . $queryStr . '%');
            })
            ->get();

        return view('gameList', compact('games'));
    }

This code works, but I don’t like that for each field it is necessary to repeat "'like', '%' . $queryStr . '%'", does anyone know if this can be done faster and without repetition

2

Answers


    1. Create a file called helpers.php in your app directory.

    2. Add this code

      if (!function_exists(‘like’)) {
      function like($query) {
      return ‘%’.$query.’%’;
      }
      }

    3. Add in your composer.json file "autoload":

      {
      "files": [
      "app/helpers.php"
      ]
      },

    4. composer dump-autoload

    5. $queryStr = like($request->query(‘search’));

    6. Replace ‘%’ . $queryStr . ‘%’ on $queryStr

    Login or Signup to reply.
  1. First, I would recommend that you keep the code as is. It is a standard way and any laravel developer will understand it at first glance.

    That being said, you are looking for eloquent macro, and your exact problem is described by genius Freek Van der Herten in https://freek.dev/1182-searching-models-using-a-where-like-query-in-laravel

    In summary you can define macro in boot method of "AppServiceProvider":

    Builder::macro('whereLike', function(string $attribute, string $searchTerm) {
       return $this->orWhere($attribute, 'LIKE', "%{$searchTerm}%");
    });
    

    and then you can use it like this:

    User::query()
       ->whereLike('name', $searchTerm)
       ->get();
    

    Please read that blog post, it goes in depth how to optimize and use this macro.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search