Support the ongoing development of Laravel.io →
Eloquent Views Blade
Last updated 2 years ago.
0

you have to do something like this:

$product = Product::with('category')->get();
return view('products.index')->with('products', $products);

This is called Eager loading. The code above will load all products and return its category as well. To access this in your view you wil have to do something like this:

@foreach ($products as $product)
    <p>This my product name {{ $product->name }}</p>
    <p>This my product category {{ $product->category->name}}</p>
@endforeach

From your post you could do something like this:

$categories = Category::with('products')->get();
return view('products.index')->with('categories', $categories);

In your view,,

@foreach ($categories as $category)
    <h1>$category->name</h1>
    
    <ul>
        @foreach ($category->products as $product)
            <li>{{ $product->name }}</li>
        @endforeach
    </ul>
@endforeach
0

Sign in to participate in this thread!

Eventy

Your banner here too?

KBS1008 kbs1008 Joined 25 Aug 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.