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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1View composers centralize the data a shared partial needs, keeping controllers free of navigation concerns.
- 2Wrapping an expensive count in cache remember trades slight staleness for far fewer database hits.
- 3Handling the guest case first lets the authenticated path assume a real user exists.
Related explainers
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-laravel-view-composer-feeds-the-navigation-explained-php-7f1f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.