In Laravel, some consultation methods do not accept callbacks.
It seems to me that you are trying to utilize the same functionality in whereSub
, where you pass a Closure
as argument and thus you can do the if
inside.
Although you can do that, the purpose of where
with callback is not making ifs, but encompassing the clause where
parenthesely.
In your case, I think you could solve this with the following maneuver: use the Model Scope do Laravel.
class Model {
public function scopeClosure($query, \Closure $callback) {
$callback($query);
return $query;
}
}
Then you do the consultation like this:
Model::where(['nome' => 'Wallace'])->closure(function ($query) use($var) {
if ($var) $query->having(...);
});
Some developers usually do it differently. They usually "dismember" the query, since Laravel uses the Fluent Interface standard. Thus, it is possible to "continue" the query you assigned to a variable.
$query = Usuario::orderBy('nome');
// Executa $query se `$var` é verdadeiro
$var && $query->having(...);
$usuarios = $query->where(['nivel_id' => 4])->paginate(15);
Updating
There are some things in Laravel that you will only discover if you have the custom of futucar the source code, as I usually do.
I just saw a feature that was developed designed in cases like yours, highlighted above. But this is a unique solution for those who use Laravel 5.2.
I just found out there’s a method called when
within the class Illuminate\Database\Query\Builder
.
The code for this method is as follows::
public function when($value, $callback)
{
$builder = $this;
if ($value) {
$builder = call_user_func($callback, $builder);
}
return $builder;
}
Link to class on GITHUB
Observing this method, we can understand that it works as follows: You pass a first argument to when
. If it is valid, it will execute the query contained within your Closure
.
It’s that simple:
$idade = 26;
Usuario::where(['nome' => 'Wallace'])->when($idade > 18, function ($query){
$query->having(....);
});
In this case above, to test the operation, simply change the value of $idade
for 17
. Everything defined in callback
of when
will be ignored.
I had already answered that.
– Wallace Maxters
Although it looks like, I will give a +1, because it is good to worry about the organization of the code :)
– Wallace Maxters
Don’t fight, I positive all of you.
– Diego Souza