skip to Main Content

The following example will give me all users that are older than $age and have the gender $gender:

public function get_users_older_than(int $age = null, string $gender = null) {
   $users = User::query()
               ->where('age', '>', $age)
               ->where('gender', $gender)
               ->get();

   return $users;
}

Is there a way to use the where clause only if age or gender is present in a more eloquent and shorter way then:

public function get_users_older_than(int $age = null, string $gender = null) {
   $users = User::query();

   if ($age) {
      $users = $users->where('age', '>', $age):
   }

   if ($gender) {
      $users = $users->where('gender', $gender):
   }

   $users = $users->get();

   return $users;
}

With that, I could avoid to create and use the extra function and just have one single arrow connected line of code.

2

Answers


  1. A shorter way to do that would be this:

    $users = User::where(function ($q) use($age, $gender) {
        if ($age) {
            $q->where('age', '>', $age);
        }
        if ($gender) {
           $q->where('gender', $gender);
        }
        })->get();
    

    But just so you know, shorter code does not guarantee more efficiency.

    Login or Signup to reply.
  2. There is also a conditional clauses function when.

    Based on what you have, that could look like:

    public function get_users_older_than(int $age = null, string $gender = null) {
        $users = User::query();
    
        $users->when($age, function ($query, $age) {
            $query->where('age', '>', $age);
        })->when($gender, function ($query, $gender) {
            $query->where('gender', $gender);
        })->get();
    
        return $users;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search