Laravel Tutorials

Early View Data Preparation with Laravel View Creators

Published
Early View Data Preparation with Laravel View Creators image

Laravel's View Creators allow you to prepare data immediately after view instantiation, earlier than View Composers, making them perfect for setting up essential view data or optimizing performance.

use Illuminate\Support\Facades\View;
// Registering a View Creator
View::creator('dashboard', DashboardCreator::class);

Let's explore a practical example of managing a dynamic application menu:

<?php
 
namespace App\View\Creators;
 
use App\Services\MenuService;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;
 
class ApplicationMenuCreator
{
protected $menuService;
 
public function __construct(MenuService $menuService)
{
$this->menuService = $menuService;
}
 
public function create(View $view)
{
$user = Auth::user();
 
$view->with([
'mainMenu' => $this->menuService->getMainMenu($user),
'quickActions' => $this->menuService->getQuickActions($user),
'recentItems' => $this->menuService->getRecentItems($user),
'notifications' => $this->menuService->getPendingNotifications($user)
]);
}
}
 
// In your AppServiceProvider
public function boot()
{
View::creator('layouts.app', ApplicationMenuCreator::class);
}
 
// Usage in layouts/app.blade.php
<div class="sidebar">
<nav>
@foreach($mainMenu as $menuItem)
<a href="{{ $menuItem['url'] }}" class="{{ $menuItem['active'] ? 'active' : '' }}">
{{ $menuItem['label'] }}
</a>
@endforeach
</nav>
 
@if(count($quickActions))
<div class="quick-actions">
@foreach($quickActions as $action)
<button onclick="handleAction('{{ $action['id'] }}')">
{{ $action['label'] }}
</button>
@endforeach
</div>
@endif
</div>

View Creators provide early data preparation for your views, ensuring critical data is available as soon as the view is instantiated.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Laravel Image Responses: Serve Resized Images From Routes image

Laravel Image Responses: Serve Resized Images From Routes

Read article
Pause All Laravel Queues During a Deploy image

Pause All Laravel Queues During a Deploy

Read article
Laravel Terminal UI for the artisan dev Command image

Laravel Terminal UI for the artisan dev Command

Read article
Pause All Queues and a New artisan dev UI in Laravel 13.25 image

Pause All Queues and a New artisan dev UI in Laravel 13.25

Read article
Laravel monitoring that doesn't bill you by your traffic image

Laravel monitoring that doesn't bill you by your traffic

Read article
Mock PHP Classes in Tests With the Double Library image

Mock PHP Classes in Tests With the Double Library

Read article