0

When() in laravel

 2 years ago
source link: https://dev.to/marcosgad/eloquent-when-in-laravel-5726
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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 modeExit 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 modeExit fullscreen mode

With use()

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

I hope you enjoy the code.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK