Grayscale profile picture

Patrique Ouimet

Senior Product Engineer

Fluid Eloquent Queries

Mon, Jan 28, 2019 9:21 PM

Fluid Eloquent Queries

This is a simple example of how to write fluid (or chained) eloquent queries rather than using if statements.

Given we have a Post model and we want to display only those from within the last week and only the featured posts.

If Statement Method

You might think to do something like this:

$posts = Post::query();

if (request('is_last_week')) {
    $posts = $posts->where('created_at', '>', Carbon::now()->subDays(7)->startOfDay());
}

if (request('is_featured')) {
    $posts = $posts->where('is_featured', true);
}

$posts = $posts->get();

Fluid Eloquent

Now let's try something different:

Post::when(request('is_last_week'), function ($query) {
    return $query->where('created_at', '>', Carbon::now()->subDays(7)->startOfDay());
})->when(request('is_featured'), function ($query) {
    return $query->where('is_featured', true);
})->get();