cyberfly
6/28/2018 - 3:05 AM

Laravel conditional query using When

function index()
{
  $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'));
  });
  
  // From Laravel 5.4 you can pass the same condition value as a parameter
  $query->when(request('role', false), function ($q, $role) { 
      return $q->where('role_id', $role);
  });
  
  $authors = $query->get();
}