Petter, if the query logic is going to repeat, it does not have to fill the "stop" of if
. I recommend you simplify your code by encapsulating query logic within a loop.
For example, you want the
primeiro_nome
,
email
, and
sobrenome
fields to be searched with
LIKE
and
nivel_id
,
idade
, and
curso
to be searched with the
=
/ p>
You would not have to make multiple ifs
, but you could do a foreach and apply the logic in there.
$callback = function ($query) use($request) {
$likes = ['primeiro_nome', 'email', 'sobrenome'];
foreach ($request->only($campos_like) as $name => $value)
{
$value && $query->where($name, 'LIKE', "%{$value}%");
}
$equals = ['nivel_id', 'idade', 'curso'];
foreach ($request->only($campos_equal) as $name => $value) {
$value && $query->where([$name => $value]);
}
};
Usuario::orderBy('primeiro_nome')->where($calback)->paginate(15)->appends($request->all());
Note that it is not necessary to fill the code with if
. If you can simplify, always simplify.
Maybe you're wondering, "But where are the ifs?"
If you look closely, I replaced if
with expression $value && $query->where(...)
. I usually do this when I want to simplify a if
. But I will not go into many details, as I have answered this before:)
Refactoring is worth it if the soul is not small!