Search code examples
laravellistcategories

How to show records filtered by specific category


this is my blade file this is my controller

how can I list a musician of a certain category in my blade file with an if?


Solution

  • If you just want to list or show musicians of a particular category on the view then you can filter the musicians in the controller method and then send the filtered data to view

    public function group()
    {
        return view('pages.group', [
            'musicians' => Musician::where('category_id', 10)->get()
        ]);
    }
    

    And then in blade view

    @foreach($musicians as $musician)
        <p>{{ $musician->musician_name }} {{ $musician->musician_surname }}</p>
    @endforeach
    

    it works thanks. but if I wanted to print on one line the musicians of the category with id 10 and on another line the musicians of the category with id 40? always on the same blade file

    public function group()
    {
        return view('musicians', [
            'categories' => Musician::get()->groupBy(function($item) {
                return $item->category_id;
            })
        ]);
    }
    
    @foreach($categories as $catetory)
        @foreach($category as $key => $musician)
            <p>{{ $musician->musician_name }} {{ $musician->musician_surname }}</p>
        @endforeach
    @endforeach