I have model category with relations of parent and children:
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function parent()
{
return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScope('active');
}
public function products()
{
return $this->hasMany(Product::class);
}
And I have Product model with relation category:
public function category()
{
return $this->belongsTo(Category::class);
}
In CategoryController I have method show:
public function show(Category $category)
{
return view('main', compact('category'));
}
In blade I show product with:
@php $products = isset($category) ? $category->products()->paginate(15) : $products; @endphp
@include('partials.products')
If isset category
variable then I get products. But this only for certain category. How I can show parent and child category title and products in this format table:
<table>
<tr>
<th>Name Product</th>
<th> Price </th>
</td>
<tr>
<td colspan=2>Parent Category title of products</td>
</tr>
<tr>
<td>Product of parent category #1</td>
<td>890 $ </td>
</tr>
<tr>
<td colspan=2>Child category title of products</td>
</tr>
<tr>
<td>Product of child category #1</td>
<td>890 $ </td>
</tr>
...
</table>
Now I have this:
<table class="table">
<tr>
<th class="th-1">Name</h2></th>
<th class="th-2">Count <!--<span><i class="fas fa-chevron-up"></i>--></span></th>
<th class="th-3">Price <!--<span><i class="fas fa-chevron-up"></i>--></span></th>
<th class="th-4">Sales <!--<span><i class="fas fa-chevron-up"></i>--></span></th>
<th class="th-5"></th>
</tr>
{{-- {{ dd($products->groupBy('category_id')) }} --}}
@php
$products = isset($category) ? $category->products()->paginate(15) : $products;
@endphp
@include('partials.products')
</table>
In partials.products
:
@forelse($products->groupBy('category.title') as $title => $prods)
<tr class="category {{ $sub ?? '' }}">
<td colspan="5">{{ $title }}</td>
</tr>
//if have parent products, write it's...
//@include('partials.product') //parent products
<tr class="category {{ $sub ?? '' }}">
<td colspan="5">{{ $subtitle }}</td>
</tr> //write category child title, if not empty with products
@include('partials.product') //child products
@empty
<tr>
<td colspan="5">
@isset($category)
<p>Items on category not found :(</p>
@endisset
</td>
</tr>
@endforelse
Please help resolve this question..