php 61 lines · 8 steps

Building a breadcrumb component in Laravel

A Blade component turns a URL path into an ordered trail of labeled, linked breadcrumbs.

Explained by highlit
1<?php
2 
3namespace App\View\Components;
4 
5use Illuminate\Support\Str;
6use Illuminate\View\Component;
7 
8class Breadcrumbs extends Component
9{
10 public array $trail;
11 
12 public function __construct(?string $path = null)
13 {
14 $path = trim($path ?? request()->path(), '/');
15 
16 $this->trail = $this->build($path);
17 }
18 
19 protected function build(string $path): array
20 {
21 $crumbs = [[
22 'label' => 'Home',
23 'url' => url('/'),
24 'current' => $path === '',
25 ]];
26 
27 if ($path === '') {
28 return $crumbs;
29 }
30 
31 $segments = explode('/', $path);
32 $accumulated = '';
33 $last = count($segments) - 1;
34 
35 foreach ($segments as $index => $segment) {
36 $accumulated .= '/' . $segment;
37 
38 $crumbs[] = [
39 'label' => $this->humanize($segment),
40 'url' => url($accumulated),
41 'current' => $index === $last,
42 ];
43 }
44 
45 return $crumbs;
46 }
47 
48 protected function humanize(string $segment): string
49 {
50 if (ctype_digit($segment)) {
51 return '#' . $segment;
52 }
53 
54 return Str::of($segment)->replace(['-', '_'], ' ')->title();
55 }
56 
57 public function render()
58 {
59 return view('components.breadcrumbs');
60 }
61}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Deriving view data in the constructor keeps templates dumb and focused on markup.
  2. 2Accumulating path segments as you loop lets each crumb link to its own partial URL.
  3. 3Small helpers like humanize centralize display formatting so labels stay consistent.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a breadcrumb component in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code