Skip to content
Advertisement

Filtering in Laravel using regex


I’m trying to filter products based on query string. My goal is to get products from a collection if it’s given, otherwise get every product. Could someone help me what’s wrong with the following code?

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

PS.: I’ve also tried with ‘regex:/[a-z]+’, it’s not working…

$products = AppProduct::where(['collection' => (request()->has('collection')) ? request('collection') : 'regex:/[a-z]+'])->get();

Advertisement

Answer

What you can do is use when eloquent clause, so your where clause for collections will be triggered only when the request('collection') exists, same logis applie to type as well.

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

Or another way if you have your request values assigned to a variable something like:

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

        $products = AppProduct::
        when(!empty($collection), function ($q) use ($collection) {
            return $q->where('collection', $collection);
        });
        ->when(!empty($type), function ($q) use ($type) {
            return $q->where('type', $type);
        })
        ->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement