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
Create a file called helpers.php in your app directory.
Add this code
if (!function_exists(‘like’)) {
function like($query) {
return ‘%’.$query.’%’;
}
}
Add in your composer.json file "autoload":
{
"files": [
"app/helpers.php"
]
},
composer dump-autoload
$queryStr = like($request->query(‘search’));
Replace ‘%’ . $queryStr . ‘%’ on $queryStr
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":
and then you can use it like this:
Please read that blog post, it goes in depth how to optimize and use this macro.