How to apply eloquent relation conditionally

September 21, 2019

by Yunus Shaikh
Here is a snippet to apply laravel eloquent relation conditionally.

    $query = Author::query();

    $query->when(request('filter_by') == 'likes', function ($q) {
        return $q->where('likes', '>', request('likes_amount', 0));
    });
    $query->when(request('filter_by') == 'date', function ($q) {
        return $q->orderBy('created_at', request('ordering_rule', 'desc'));
    });
    
    $authors = $query->get();