competitiveoverwatch tip

Eloquent::when() – no more if-else’s

Many of us write conditional queries with “if-else”, something like this:

1if (request('filter_by') == 'likes') {2    $query->where('likes', '>', request('likes_amount', 0));3}4if (request('filter_by') == 'date') {5    $query->orderBy('created_at', request('ordering_rule', 'desc'));6}

But there’s a better way – to use when():

1$query = Author::query();2$query->when(request('filter_by') == 'likes', function ($q) {3    return $q->where('likes', '>', request('likes_amount', 0));4});5$query->when(request('filter_by') == 'date', function ($q) {6    return $q->orderBy('created_at', request('ordering_rule', 'desc'));7});

It may not feel shorter or more elegant, but the most powerful is passing of the parameters:

1$query = User::query();2$query->when(request('role', false), function ($q, $role) {3    return $q->where('role_id', $role);4});5$authors = $query->get();