How does "when" statement works in laravel?

by elisha_langworth , in category: PHP Frameworks , 2 months ago

How does "when" statement works in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 2 months ago

@elisha_langworth 

In Laravel, the "when" statement is a conditional method that can be used to conditionally add clauses to a query builder. The "when" statement takes two arguments - a boolean value and a closure. If the boolean value is true, the closure will be executed, allowing you to add additional conditions to the query builder.


Here is an example of how the "when" statement can be used in Laravel:

1
2
3
4
5
6
7
8
$users = DB::table('users')
    ->when($request->has('name'), function ($query) use ($request) {
        return $query->where('name', $request->name);
    })
    ->when($request->has('email'), function ($query) use ($request) {
        return $query->where('email', $request->email);
    })
    ->get();


In this example, the "when" statement is used to conditionally add a "where" clause to the query builder based on the presence of certain parameters in the request. If the "name" parameter is present in the request, a "where" clause will be added to filter the results by name. If the "email" parameter is present, a "where" clause will be added to filter the results by email.


Overall, the "when" statement provides a convenient way to dynamically add conditions to a query builder in Laravel based on certain conditions.