Laravel雄辩地获得所有如果变量为空 [英] Laravel eloquent get all if variable is null

查看:96
本文介绍了Laravel雄辩地获得所有如果变量为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型用户,我想按城市搜索用户,但是如果城市变量为null,则希望所有用户

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

我的代码是这样的

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

但是如果城市变量为null,则查询不返回任何内容

but if the city varible is null the query return nothing

我是这个

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

还有这个

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

推荐答案

1..您可以使用 where()关闭:

1. You could use where() closure:

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

2..您可以使用 when() :

2. You could use when():

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

3..执行此操作:

$users = User::orderBy('created_at');

if ($city) {
    $users = $users->where('city', $city);
}

$users = $users->paginate(10);

这篇关于Laravel雄辩地获得所有如果变量为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆