使用正则表达式在Laravel中过滤

问题描述 投票:0回答:1

我正在尝试根据查询字符串过滤产品。我的目标是从集合中获取产品(如果有的话),否则获取所有产品。有人可以帮我以下代码有什么问题吗?

$products = \App\Product::where([
'collection' => (request()->has('collection')) ? request('collection') : '[a-z]+',
'type' => (request()->has('type')) ? request('type') : '[a-z]+'
])->get();

PS .:我也尝试过'regex:/ [a-z] +',它不起作用...

$products = \App\Product::where(['collection' => (request()->has('collection')) ? request('collection') : 'regex:/[a-z]+'])->get();
regex laravel laravel-5
1个回答
0
投票

[您可以做的是使用when雄辩的子句,因此,仅当request('collection')存在时,才会触发用于集合的where子句,同样也要键入相同的logis。

$products = \App\Product::
when(request()->has('collection'), function ($q) {
    return $q->where('collection', request('collection'));
});
->when(request()->has('type'), function ($q) {
    return $q->where('type', request('type'));
});

或者如果将request值分配给类似变量的另一种方法:

$collection = request('collection');
$type= request('type');

    $products = \App\Product::
    when(request()->has('collection'), function ($q) use ($collection) {
        return $q->where('collection', $collection);
    });
    ->when(request()->has('type'), function ($q) use ($type) {
        return $q->where('type', $type);
    });
© www.soinside.com 2019 - 2024. All rights reserved.