DEV Community

Morcos Gad
Morcos Gad

Posted on

When() in laravel

Let's get started quickly
Sometimes you may want certain query clauses to apply to a query based on another condition

$role = $request->input('role');
$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();
Enter fullscreen mode Exit fullscreen mode

Laravel Eloquent when method will execute the given callback when the first argument given to the method evaluates to true

$collection = collect([1, 2, 3]);

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all(); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

With use()

->when($request->user_id, function ($query) use ($request) {
        return $query->where('user_id', $request->user_id);
})->get();
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy the code.

Top comments (0)