Reputation: 3375
I'm new to Laravel and trying to learn a bit while I build "real world" project.
My project is classified site. Currently I'm on step where I should show all categories, sub-categories and number of items under each sub-category.
In the database I story all categories (main and sub) in table called categories
. There is column called parent_id
which is the ID of the parent category (if is sub-category).
In the model Category.php
I have
public function item()
{
return $this->hasMany('Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id, $parent_id )
{
if( $parent_id == 0)
{ // for root-caregory
$ids = Category::select('id')->where('parent_id', $category_id)->get();
$array = array();
foreach ($ids as $id)
{
$array[] = $id->id;
}
return Item::whereIn('category_id', $array )->count();
}
else
{
return Item::where('category_id', $category_id)->count();
}
}
In my controller
public function index()
{
$Category = new Category;
$allCategories = $Category->getCategories();
return view('frontend.home', compact('allCategories'));
}
In the view this is how I showed the parent categories
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>/li>
@endforeach
What I've tried for the sub-categories is to add one if
inside the foreach
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>
<ul class="sub-category">
@if ($cats->children())
<li><a href="#"> {{ $cats->children->title }} </a></li>
@endif
</ul>
</li>
@endforeach
The error is
Undefined property: Illuminate\Database\Eloquent\Collection::$title
When I {{ dd($allCategories) }}
I see that they are in the array.
Upvotes: 2
Views: 948
Reputation: 8242
Your children
relation will return a collection and not a single model, because of this you have to loop through the children aswell:
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>
<ul class="sub-category">
@if($cats->children)
@foreach($cats->children as $child)
<li><a href="#"> {{ $child->title }} </a></li>
@endforeach
@endif
</ul>
</li>
@endforeach
Upvotes: 0