Petter, if the logic of the query is going to repeat, there is no reason to fill "the parade" of if
. I recommend that you simplify your code by encapsulating the query logic within a loop.
For example, you want the fields primeiro_nome
, email
and sobrenome
are researched with LIKE
and nivel_id
, idade
and curso
are searched with the operator =
.
You wouldn’t need to do several ifs
, but could make a foreach and apply logic inside.
$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());
Please note that the code does not need to be filled in if
. If you can simplify, always simplify.
Maybe you’re wondering, "But where are the ifs"?
If you look closely, I’ve replaced the if
by the expression $value && $query->where(...)
. I usually do that when I want to simplify a if
. But I won’t go into too much detail, because I’ve answered that before :)
Refactoring is worth it if the soul is not small!
In codeigniter I would do that way ai you propose, I found the most sensible way
– Sr. André Baill
I think that model is fine, but I have a question: in which cases would I enter the last
if($outro)
? In that structure that showed why it does notelse if..
, not the need to do the remaining checks after a returnTrue
...$consulta
will always be the last condition you enter– Miguel
It’s just an example I left not to increase the code in my question, but it can be any filter. City, Neighborhood... Sex...
– Diego Souza
I think you’re doing the right thing
– Miguel
That question seems to be duplicated, I answered it here one day
– Wallace Maxters
Possible duplicate of Laravel - Use 'WHERE' if value is different from 'NULL'
– Wallace Maxters
@Andrébaill think that indepentende to be Codeigniter or Laravel, the logic is the same. And the simplification should also be the same. It does not seem wise to fill the code with ifs, which will check the same thing, but for different values.
– Wallace Maxters