I have just started to learn Laravel 5, so I hope my question is not too stupid. I am trying to achieve the following. I have 3 tables
adverts categories advert_category
In my categories table I have main and subcategories. So parent categories have got parent_id NULL otherwise they show the id of the parent. When I save a new advert, I have the advert_id and the category_id saved in the pivot table advert_category. All that works fine. I am now trying the following. I want a Navigation with Maincategories and Subcategories shown. When I click on a Subcategory then I can read out easily the advert_id's from the advert_category table, because I am only looking for only 1 category_id, but I now plan to be able to click on the Maincategory and now show all the Adverts which belong to all the Subcategories from this Maincategory. So my approach is the following:
// Look up if passed id is found under parent_id column
$cat = Category::where('parent_id', $id)->get();
// The choosen category is a maincategory,
// therefore build dynamic where to look for all the id's
if (count($cat) > 0)
{
$query = Category::select();
foreach($cat as $value)
{
$query->orWhere('id', '=', $value->id);
}
$advertList = $query->get();
}
else{
$advertList = Category::findOrFail($id);
}
return view ('publicpage.adverts.showall',['advertList' => $advertList->adverts]);
Unfortunately, when I go on the Maincategory, I get below error. When I go on the Subcategory, I get the adverts shown.
Undefined property: Illuminate\Database\Eloquent\Collection::$adverts
A dd($advertlist) brings the following result:
Clicked on Maincategory:
Collection {#203 ▼
#items: array:2 [▼0 => Category {#204 ▶}
1 => Category {#205 ▶}
] }
So it shows Collection.
Clicked on Subcategory
Category {#201 ▼
#table: "Categories"
#connection: null
I can see that there is obviously a difference, but I have got no idea, how to fix that or what the best approach would be. I hope I explained it well enough to understand my task and look forward to any advice. Thanks in advance !
UPDATE
After the below comment, I tried it out:
// Look up if passed id is found under parent_id column
$cat = Category::where('parent_id', $id)->get();
if (count($cat) > 0)
{
$query = Category::select();
foreach($cat as $value)
{
$query->orWhere('id', '=', $value->id);
}
$advertList = $query->get();
return view ('frontend.adverts.showall',['advertList' => $advertList[0]->adverts]);
}
else{
// 1 Category,
$advertList = Category::findOrFail($id);
return view ('frontend.adverts.showall',['advertList' => $advertList->adverts]);
}
This way I get the adverts for the first category, but how would I manage to hand over the adverts for all the categories or how can I handle this? I just don't seem to to be able to fix this problem. Or would the change be in the view? I tried it with another foreach in the view aswell to run through the adervertList, but again no success. Any advice? Thank you very much in advance!