laravel过滤器if-else语句不起作用



我试图过滤我的产品中的价格性别颜色以下是我使用类似url localhost/category/tag时的工作代码?价格=100

if (request()->has('gender')) {
$products = Product::withAllTags($tags)->where('gender', request('gender'))->get();
}
if (request()->has('price')) {
$products = Product::withAllTags($tags)->where('price', '<=', request('price'))->get();
}
if (request()->has('color')) {
$products = Product::withAllTags($tags)->whereHas('colors', function ($query) {
$query->where('name', request('color'));
})->paginate(20);
}
if (request()->has('brand')) {
$products = Product::withAllTags($tags)->whereHas('brands', function ($query) {
$query->where('name', request('brand'));
})->orderBy('created_at', 'desc')->paginate(20);
}

但当url为localhost/category/tag 时出错

Undefined variable: products

我试着添加其他条件,比如

if (request()->has('gender')) {
$products = Product::withAllTags($tags)->where('gender', request('gender'))->get();
}
if (request()->has('price')) {
$products = Product::withAllTags($tags)->where('price', '<=', request('price'))->get();
}
if (request()->has('color')) {
$products = Product::withAllTags($tags)->whereHas('colors', function ($query) {
$query->where('name', request('color'));
})->paginate(20);
}
if (request()->has('brand')) {
$products = Product::withAllTags($tags)->whereHas('brands', function ($query) {
$query->where('name', request('brand'));
})->orderBy('created_at', 'desc')->paginate(20);
}
else  {
$products = Product::withAllTags($tags)->orderBy('created_at', 'desc')->paginate(20);
}  

它在localhost/category/tag上工作但是现在过滤器在localhost/category/tag上不起作用?价格=100所有数据都显示对不起我的语法

你基本上是在做

if (request()->has('brand')) {
$products = Product::withAllTags($tags)->whereHas('brands', function ($query) {
$query->where('name', request('brand'));
})->orderBy('created_at', 'desc')->paginate(20);
}
else  {
$products = Product::withAllTags($tags)->orderBy('created_at', 'desc')->paginate(20);
}  

这使得else语句适用于request()->has('brand')将所有条件包装在if语句中,其余条件包装在一个else语句中

if(request()->has('gender')||request()->has('price')||request()->has('color')||request()->has('brand')){
if (request()->has('gender')) {
$products = Product::withAllTags($tags)->where('gender', request('gender'))->get();
}
if (request()->has('price')) {
$products = Product::withAllTags($tags)->where('price', '<=', request('price'))->get();
}
if (request()->has('color')) {
$products = Product::withAllTags($tags)->whereHas('colors', function ($query) {
$query->where('name', request('color'));
})->paginate(20);
}
if (request()->has('brand')) {
$products = Product::withAllTags($tags)->whereHas('brands', function ($query) {
$query->where('name', request('brand'));
})->orderBy('created_at', 'desc')->paginate(20);
}
}
else  {
$products = Product::withAllTags($tags)->orderBy('created_at', 'desc')->paginate(20);
}  

最新更新