PHP [SOLVED]: Laravel eloquent get all if variable is null

PHP [SOLVED]: Laravel eloquent get all if variable is null

Home Forums Scripting PHP Tutorials PHP [SOLVED]: Laravel eloquent get all if variable is null

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245544

    Cloudy Point
    Keymaster

    QuestionQuestion

    i have a model User and i want search user by city but if the city varible is null a want all user

    my code like this

    User::where('city', $city)->orderBy('created_at')->paginate(10);
    

    but if the city varible is null the query return nothing

    i thy this

     User::doesntHave('city')->get();
    

    and this

    User::whereHas('city')->get();
    

    I know i can read my code like this

      if($city){
         User::where('city', $city)->orderBy('created_at')->paginate(10);
      } else {
        User::orderBy('created_at')->paginate(10);
    }
    

    but a want add other varible in my query and is not perfect

    #245545

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    1. You could use where() closure:

    User::where(function ($q) use($city) {
        if ($city) {
            $q->where('city', $city);
        }
    })->orderBy('created_at')->paginate(10);
    

    2. You could use when():

    User::when($city, function ($q) use ($city) {
        return $q->where('city', $city);
    })->orderBy('created_at')->paginate(10);
    

    3. Do this:

    $users = User::orderBy('created_at');
    
    if ($city) {
        $users = $users->where('city', $city);
    }
    
    $users = $users->paginate(10);
    

    Source: https://stackoverflow.com/questions/48027886/laravel-eloquent-get-all-if-variable-is-null
    Author: Alexey Mezenin
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.