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 IlluminateSupportFacadesView;
// Registering a View Creator
View::creator('dashboard', DashboardCreator::class);
Let’s explore a practical example of managing a dynamic application menu:
<?php
namespace AppViewCreators;
use AppServicesMenuService;
use IlluminateViewView;
use IlluminateSupportFacadesAuth;
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.
The post Early View Data Preparation with Laravel View Creators appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ