[英]laravel filter if else statement is not working
我嘗試按價格性別顏色過濾產品,這是當我使用類似url localhost / category / tag?price = 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上不工作?price = 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.