I don't think I understand the proper use of when()
.
I'm trying to use it in this fashion:
I have a jsonb
column (called info
) which has multiple properties. I want to check if one of the values is 'Chemical' and perform some query. Otherwise, perform another query. This is how I am using it:
$query->when(
'info->type' === 'Chemical',
function ($query) {
return $query->has('bottles', 0);
},
function ($query) {
return $query->where('info->quantity', '<=', 0);
}
);
The first function would be the truthy value and the second function would be falsey. However, it never hits the first function.
What am I doing wrong? Is this not how you use when
?
CodePudding user response:
You are correct, the only error is that info->type
is never going to be equal to Chemical
because you are comparing strings.
So, whatever you write as the expression, it must literally be something that has nothing to do with the query.
when
works as an alias of an if
, so you don't need to break your query like this:
$query = Model::query();
if ($expression) {
$query->where('column_a', 1);
} else {
$query->where('column_a', 0);
}
$query->where('whatever', 123);
if ($expression2) {
$query->where('abc', 1);
}
Using when
, it would be like this:
$query = Model::query()
->when(
$expression,
fn (Builder $query) => $query->where('column_a', 1),
fn (Builder $query) => $query->where('column_a', 0),
)
->when(
$expression2,
fn (Builder $query) => $query->where('abc', 1)
);
Following your example, you will need to get what info->type
is, let's say you are able to get that from another part:
$infoType = 'value';
$query = Model::query()
->when(
$infoType === 'Chemical',
function ($query) {
return $query->has('bottles', 0);
},
function ($query) {
return $query->where('info->quantity', '<=', 0);
}
);
More about when
on the documentation.
You can read more by just checking the when()
's source code (Laravel 9)