Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Luka's avatar
Level 1

How to build dynamic query for Eloquent Model and pass to view

Hi everybody,

I have just started to learn Laravel 5 and 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 chosen 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

In the View, I try to print it out like this:

@foreach($advertList as $advertDetail)

          {{ $advertDetail->title }}

          

@endforeach

I get the adverts printed for the subcategory, but as I said an Error when I click on the maincategory, which involves multiple subcategories. Where is my mistake? In the Controller or the way I try to access the information in the view? Could someone help? Thank you in advance.

0 likes
2 replies
Luka's avatar
Level 1

Thank you very much for your reply. I just realised that I would have to subscribe to watch a Video lesson. I am sorry that I did not realise this before, I thought this is just a Laravel Forum. Anyway, maybe I will be able to find something about Query String Filtering, since this seems to be the direction you wanted me to look at. Thank you very much again for this.

Please or to participate in this conversation.