Ask Your Question
4

In Laravel, how does the "when" statement function?

asked 2023-06-06 18:30:50 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-06 18:44:01 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 18:30:50 +0000

Seen: 17 times

Last updated: Jun 06 '23