Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

madsynn's avatar

Query Builder for my shop filters

Hi everyone,

I need some guidance on how to setup my queries for my shop filters.

Tables:

products product_categories

How would i return all products with a category id from ajax request.

Lets say the id from the request is 17 how would i query the db to return all products with a product_category of 17?

thank you in advance.

0 likes
3 replies
MichalOravec's avatar
Level 75

If you have setted your relationship then

$products = Product::whereHas('categories', function ($query) use ($request) {
    $query->where('id', $request->category_id);
})->get();

Docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

You can also use a condional clause

$products = Product::when($request->category_id, function ($query, $categoryId) {
    return $query->whereHas('categories', function ($query) use ($categoryId) {
        $query->where('id', $categoryId);
    });
})->get();

Docs: https://laravel.com/docs/8.x/queries#conditional-clauses

1 like
madsynn's avatar

@michaloravec

Quick question for you. I have the filter working but instead of outputting the $data to my loop it keeps outputting json code to the page instead. I have never seen this happen any idea how to stop it.

Here is my loop for the $data.

@foreach($data as $product)
{{$product->name}}
@endforeach

I have tried all of the following but no luck.

return  response()->json(['data' => $data]);

return $data

return view('shop', compact('data'));

Any help would be appreciated as im not sure why it keeps spitting json out instead of using the loop.

MichalOravec's avatar

I don't know what you are doing, but this should be in the controller

$products = Product::when($request->category_id, function ($query, $categoryId) {
    return $query->whereHas('categories', function ($query) use ($categoryId) {
        $query->where('id', $categoryId);
    });
})->get();

return view('shop', compact('products'));

and this in the view

@foreach($products as $product)
    {{ $product->name }}
@endforeach

Please or to participate in this conversation.