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

jginorio's avatar

How to display a breadcrumb from root the category to the product's category

Goal:

On my product's detail page I want to display a breadcrumb of all the parent categories that my product has.

For example, if there is a product that is assigned a category_id pointing to a SubSubCategory; I want the breadcrumb to be:

Root Category / SubCategory / SubSubCategory

Problem:

Some products might a category_id that points to the root category (has no children) and other products might have a category_id that points to a category that is 2 levels deep (has two parents). How do I handle these scenarios?

What I have tried:

This is my https://i.stack.imgur.com/anCRh.png

This is my https://i.stack.imgur.com/g1iHS.png

So far, if I wanted to get the category breadcrumb of a specific product I would do it like this:

{{$product->category->parent->name}} / {{$product->category->name}}

But it quickly had errors with the products that had a root category assigned to them. Because I was trying to get a relationship that didn't exist.

0 likes
2 replies
MichalOravec's avatar

@jginorio Maybe something like this

@if ($rootCategory = $product->category->parent->parent->name ?? null)
    {{ $rootCategory }} /
@endif

@if ($subCategory = $product->category->parent->name ?? null)
    {{ $subCategory }} /
@endif

{{ $product->category->name }}

But will be propably need to use nested eager loading

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

Or you can make some own helper, and call there your categories recursive.

1 like

Please or to participate in this conversation.