Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent get all if variable is null

Tags:

php

mysql

laravel

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

like image 367
john Avatar asked Dec 29 '17 20:12

john


1 Answers

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);
like image 165
Alexey Mezenin Avatar answered Oct 22 '22 19:10

Alexey Mezenin