Laravel get all records who have category
<p>So I've been struggling with this for a while now.
I wan't to get all 'products' which contain a certain pivot <code>category</code>.</p>

<p>So I have a route:</p>

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

<p>And a Product model with:</p>

<pre><code>public function categories()
{
    return $this-&gt;belongsToMany(Category::class);
}
</code></pre>

<p>And then my controller:</p>

<pre><code>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-&gt;categories;
        foreach($categories as $category) {

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

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

    return view('pages.category-products', compact('products', 'category'));
}
</code></pre>

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

<pre><code>$products = Product::with('categories.title', $categoryUrl)-&gt;get();
</code></pre>

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

<p>I hope someone can help me out.</p>

<p>Thanks!</p>