In Laravel, the "when" statement allows for conditional queries. It is used to conditionally add clauses to the query.
The structure of the "when" statement is as follows:
->when($condition, $callback, $default = null)
$condition
: the condition to be evaluated. It will be passed to the $callback
function as the first argument.$callback
: the function to be executed when the $condition
is true. It should contain the clauses to be added to the query.$default
(optional): the function to be executed when the $condition
is false. It should also contain the clauses to be added to the query.Here is an example of the "when" statement in action:
$query = DB::table('users')
->when($request->has('active'), function ($query) {
return $query->where('active', true);
})
->get();
In this example, if the $request
includes a parameter called "active", the query will add a where
clause to filter by active users. If the parameter is not included in the request, the query will not add any extra clauses.
Asked: 2023-06-06 18:30:50 +0000
Seen: 17 times
Last updated: Jun 06 '23