user9953513
user9953513

Reputation:

laravel How to display items of one category on the relationship between item and category tables

I asked this question before but didnt get any answer,hope you have the solution. As I have 2 tables, items and categories so every item has one category and one category can have many items. my problem is when using groupby function but it shows one item for every category

item model:

 class Item extends Model
{
 protected $table="items";
protected $fillable= 
['item_title','category_id','item_price','item_details','item_image'];
protected $primaryKey='item_id';
public $timestamps=false;

public function categories()
{
$this->hasOne('App\category','category_id','category_id');
}
}

category model

class Category extends Model
{
protected $table="categories";
protected $fillable=['category_name'];
protected $primaryKey='category_id';
public $timestamps=false;

  public function items()
  {
    $this->hasMany('App\items','category_id','category_id');
  }
  }

Controller

class HomeController extends Controller
{
public function getItems()
{
$items = Item::groupBy('category_id')->get();   
return view('home',compact('items'));
}
}

HTML

 @foreach($items as $indexKey => $item)
<div class="MenuPage_contentArea">
<div class="Category_root" id="one">
<div class="Category_categoryHeader">

<div><h2 class="Category_name">{{$item->item_category}}</h2></div>
<div class="Category_description"></div>
</div>

  <div class="Category_itemsContainer">
  <div class="Category_itemContainer">
  <button class="Item_root Button_root">
  <div class="Item_image" style="background-image: url('{{ asset('images/' . $item->item_image) }}');"></div>

<div class="Item_itemContent">
<div class="Item_topSection">
<span class="Item_name">{{$item->item_title}}</span>

<span class="Item_price">${{$item->item_price}}</span></div>
<div class="Item_description">{{$item->item_details}}</div>
</div>
</button>
</div>
</div>
</div>
</div>
@endforeach

Upvotes: 0

Views: 1488

Answers (1)

Ruman
Ruman

Reputation: 191

You are grouping at SQL level, but if you want all of the items in a category grouped in a Collection, then use groupBy method from Collection. Use all() method to get a collection of all items, then use groupBy() method to group the items by category_id:

HOME CONTROLLER

class HomeController extends Controller

{
    public function getItems()
    {
        $items = Item::all()->groupBy('category_id');   
        return view('home',compact('items'));
    }
}

Access in your blade File as:

@foreach($items as $category_id => $categoryItems)
   Category ID: {{ $category_id }} <br>
   @foreach($categoryItems as $item)
     <!-- Display Item Details Here -->
   @endforeach
@endforeach

Hope it helps you. :)

Upvotes: 1

Related Questions