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();
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]
With use()
->when($request->user_id, function ($query) use ($request) {
return $query->where('user_id', $request->user_id);
})->get();
I hope you enjoy the code.
Top comments (0)