php 46 lines · 5 steps

How a Laravel view composer feeds the navigation

A view composer injects per-user navigation data — cached unread counts and quick links — into a shared view.

Explained by highlit
1<?php
2 
3namespace App\View\Composers;
4 
5use App\Models\Notification;
6use Illuminate\Contracts\Auth\Factory as AuthFactory;
7use Illuminate\Contracts\Cache\Repository as Cache;
8use Illuminate\View\View;
9 
10class NavigationComposer
11{
12 public function __construct(
13 protected AuthFactory $auth,
14 protected Cache $cache,
15 ) {
16 }
17 
18 public function compose(View $view): void
19 {
20 $user = $this->auth->guard()->user();
21 
22 if (! $user) {
23 $view->with([
24 'unreadNotifications' => 0,
25 'quickLinks' => [],
26 ]);
27 
28 return;
29 }
30 
31 $unread = $this->cache->remember(
32 "user.{$user->id}.unread_notifications",
33 now()->addMinutes(5),
34 fn () => Notification::query()
35 ->where('user_id', $user->id)
36 ->whereNull('read_at')
37 ->count(),
38 );
39 
40 $view->with([
41 'currentUser' => $user,
42 'unreadNotifications' => $unread,
43 'quickLinks' => $user->quickLinks()->orderBy('position')->get(),
44 ]);
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1View composers centralize the data a shared partial needs, keeping controllers free of navigation concerns.
  2. 2Wrapping an expensive count in cache remember trades slight staleness for far fewer database hits.
  3. 3Handling the guest case first lets the authenticated path assume a real user exists.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Laravel view composer feeds the navigation — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code