chrisgrim's avatar

Creating Brand Categories

Hi, Right now on my index blade I am using

@foreach ($brands as $brand)
@if ($brand->channel_id == 1)
@endif 
@endforeach 
---
@foreach ($brands as $brand)
@if ($brand->channel_id == 2)
@endif 
@endforeach 

My index method is

public function index(Channel $channel)
    {
        if ($channel->exists) {
            $brands = $channel->brands()->latest()->get();
        } else {
            $brands = Brand::latest()->get();
        }

        return view('brands.index', compact('brands'));
    }

This does work except when I try to add pagination. Then it only shows first foreach and never makes it to the second or third. I am guessing there is a better way to do category sections on my index page.

Thanks!

0 likes
2 replies
m7vm7v's avatar

You need to make a few tweaks

public function index(Channel $channel)
{
        if ($channel->exists) {
            $brands = $channel->brands()->latest();
        } else {
            $brands = Brand::latest();
        }

        return view('brands.index', ['brands' => $brands->paginate(15)]);
}

And in you view -

<div class="container">
    @foreach ($brands as $brand)
        @if($brand->channel_id == 1)
        //do something
    @endif
        @if($brand->channel_id == 2)
        //do something
    @endif
    @endforeach
</div>

{{ $brands->links() }}

Have a good read at https://laravel.com/docs/5.7/pagination

chrisgrim's avatar

Hi @m7vm7v

Yeah I see this, but I am still having issues with the pagination. If I say paginate(4) because I only want each category section to show 4 brands on the index page this solution doesn't work. I only see the first 4 posts with the channel_id ==1. I am looking for a way to show 4 brands for each category on the first page.

Please or to participate in this conversation.