Search code examples
phplaravellaravel-5categorieswebshop

Laravel get all records who have category


So I've been struggling with this for a while now. I wan't to get all 'products' which contain a certain pivot category.

So I have a route:

Route::get('products/{category}', ['as' => 'category.products', 'uses' => 'ProductsController@getCatProducts']);

And a Product model with:

public function categories()
{
    return $this->belongsToMany(Category::class);
}

And then my controller:

public function getCatProducts($categoryUrl)
{
    $products = Product::get();

    $productsWithCat = [];

    // loop through all projects
    foreach($products as $product) {

        // loop through all categories assigned to product
        $categories = $product->categories;
        foreach($categories as $category) {

            // check if product has category from url
            if ($category->title == $categoryUrl) {
                array_push($productsWithCat, $product);
            }
        }
    }

    $category = $categoryUrl;
    $products = $productsWithCat;

    return view('pages.category-products', compact('products', 'category'));
}

So this works, but there is probably a much better way of doing this. Something like:

$products = Product::with('categories.title', $categoryUrl)->get();

Also my way returns an array and not a collection anymore, so I can't even get to the categories in my blade.

I hope someone can help me out.

Thanks!


Solution

  • There is a much better way and you were close...

    $products = Product::with('categories')
        ->whereHas('categories', function($q) use ($categoryUrl) {
            $q->where('title', $categoryUrl);
        })->get();