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

biswa1shaw's avatar

Nested Eager loading with optional where clause

I am using eloquent with slim framework, but I seem to be stuck on a problem involving multilevel eager loading with optional where clause. A little context about the problem first.

There are 3 tables Category, Sub_category and Child_category.

The sub_category table has a column 'category_id' which is a foreign key to 'id' of Category table.

The child_category table has a column 'sub_category_id' which is a foreign key to 'id' of sub_category table

I have been successful in fetching all the data from the tables as per the hierarchy with the following

$categoryHierarchy = Category::with([
      'subCategories' => function ($query) {
        $query->select('id', 'category_id', 'name');
      },
      'subCategories.childCategories' => function ($query) {
        $query->select('id', 'sub_category_id', 'name');
      }
    ])
    ->select('id', 'name', DB::raw('CONCAT("'.$_SERVER['SERVER_NAME'].'/",carousel_image) AS image'))->get();

Now as a part of an API I need to get all/partial data from this hierarchy

i.e. if a category_id is provided, I need to provide the hierarchy of that category alone.

If a subcategory id is provided (along with category id), then only the relevent category, subcategory and all its child categories will be provided

Likewise, the api can filter out the child category as well (along with category and sub_category)

I have tried doing it 'whereHas' but it returned an empty dataset.

Any help is greatly appreciated.

0 likes
0 replies

Please or to participate in this conversation.