Early View Data Preparation with Laravel View Creators

Last updated on by

Early View Data Preparation with Laravel View Creators image

Laravel View Creators execute immediately when views are instantiated, providing an earlier injection point than View Composers for preparing essential data required throughout the view rendering lifecycle.

View Creators differ from View Composers in their execution timing - they run right after view instantiation rather than just before rendering:

use Illuminate\Support\Facades\View;
use App\View\Creators\UserDataCreator;
 
public function boot()
{
View::creator('dashboard', UserDataCreator::class);
}

Create the corresponding creator class with dependency injection support through the constructor.

namespace App\View\Creators;
 
use App\Services\UserMetricsService;
use Illuminate\View\View;
 
class UserDataCreator
{
protected $metricsService;
 
public function __construct(UserMetricsService $metricsService)
{
$this->metricsService = $metricsService;
}
 
public function create(View $view)
{
$view->with('totalUsers', $this->metricsService->getTotalCount());
}
}

Here's a comprehensive sidebar widget system that demonstrates View Creator capabilities:

namespace App\View\Creators;
 
use Illuminate\View\View;
use App\Services\WidgetService;
use App\Services\PermissionService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
 
class SidebarCreator
{
protected $widgetService;
protected $permissionService;
 
public function __construct(WidgetService $widgetService, PermissionService $permissionService)
{
$this->widgetService = $widgetService;
$this->permissionService = $permissionService;
}
 
public function create(View $view)
{
$user = Auth::user();
 
if (!$user) {
$view->with('sidebarWidgets', []);
return;
}
 
$cacheKey = "sidebar_widgets_user_{$user->id}";
 
$widgets = Cache::remember($cacheKey, 300, function () use ($user) {
return $this->buildUserWidgets($user);
});
 
$view->with('sidebarWidgets', $widgets);
$view->with('widgetPermissions', $this->permissionService->getUserWidgetPermissions($user));
}
 
private function buildUserWidgets($user)
{
$availableWidgets = $this->widgetService->getAvailableWidgets();
$userPreferences = $user->widget_preferences ?? [];
 
$widgets = [];
 
foreach ($availableWidgets as $widget) {
if (!$this->permissionService->canAccessWidget($user, $widget['key'])) {
continue;
}
 
$isEnabled = $userPreferences[$widget['key']]['enabled'] ?? $widget['default_enabled'];
$position = $userPreferences[$widget['key']]['position'] ?? $widget['default_position'];
 
if ($isEnabled) {
$widgets[] = [
'key' => $widget['key'],
'title' => $widget['title'],
'component' => $widget['component'],
'position' => $position,
'data' => $this->widgetService->loadWidgetData($widget['key'], $user),
'refresh_interval' => $widget['refresh_interval'] ?? 300
];
}
}
 
usort($widgets, fn($a, $b) => $a['position'] <=> $b['position']);
 
return $widgets;
}
}
 
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::creator('layouts.main', SidebarCreator::class);
View::creator('layouts.dashboard', SidebarCreator::class);
}
}
 
class WidgetService
{
public function getAvailableWidgets()
{
return [
[
'key' => 'recent_activity',
'title' => 'Recent Activity',
'component' => 'widgets.recent-activity',
'default_enabled' => true,
'default_position' => 1,
'refresh_interval' => 60
],
[
'key' => 'performance_metrics',
'title' => 'Performance Metrics',
'component' => 'widgets.performance-metrics',
'default_enabled' => false,
'default_position' => 2,
'refresh_interval' => 300
],
[
'key' => 'notifications_summary',
'title' => 'Notifications',
'component' => 'widgets.notifications-summary',
'default_enabled' => true,
'default_position' => 3,
'refresh_interval' => 30
]
];
}
 
public function loadWidgetData($widgetKey, $user)
{
return match($widgetKey) {
'recent_activity' => $this->getRecentActivity($user),
'performance_metrics' => $this->getPerformanceMetrics($user),
'notifications_summary' => $this->getNotificationsSummary($user),
default => []
};
}
 
private function getRecentActivity($user)
{
return $user->activities()
->latest()
->limit(5)
->with('subject')
->get()
->map(fn($activity) => [
'description' => $activity->description,
'created_at' => $activity->created_at->diffForHumans(),
'subject_type' => class_basename($activity->subject_type),
'icon' => $this->getActivityIcon($activity->description)
]);
}
 
private function getPerformanceMetrics($user)
{
return [
'tasks_completed_today' => $user->tasks()->whereDate('completed_at', today())->count(),
'average_completion_time' => $user->tasks()->avg('completion_time_minutes'),
'productivity_score' => $this->calculateProductivityScore($user),
'weekly_trend' => $this->getWeeklyTrend($user)
];
}
 
private function getNotificationsSummary($user)
{
$unreadCount = $user->unreadNotifications()->count();
$priorityCount = $user->unreadNotifications()->where('data->priority', 'high')->count();
 
return [
'unread_total' => $unreadCount,
'high_priority' => $priorityCount,
'latest_notifications' => $user->notifications()
->limit(3)
->get()
->map(fn($notification) => [
'title' => $notification->data['title'] ?? 'Notification',
'time' => $notification->created_at->diffForHumans(),
'read' => !is_null($notification->read_at)
])
];
}
}

View Creators excel at preparing foundational data that subsequent view logic depends on, optimizing the rendering pipeline and ensuring consistent data availability across your Laravel application.

Harris Raftopoulos photo

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

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Toolkit: Reusable AI Tools for the Laravel AI SDK image

Toolkit: Reusable AI Tools for the Laravel AI SDK

Read article
Laracon US 2026 Reveals Its Full Speaker Lineup image

Laracon US 2026 Reveals Its Full Speaker Lineup

Read article
The State of PHP 2026 Survey Is Now Open image

The State of PHP 2026 Survey Is Now Open

Read article
Version-Controlled Documentation Inside Your Laravel App with Laradocs image

Version-Controlled Documentation Inside Your Laravel App with Laradocs

Read article
Typed Translation Accessors in Laravel 13.15.0 image

Typed Translation Accessors in Laravel 13.15.0

Read article
Refresh Your Laravel Database Without Dropping Every Table image

Refresh Your Laravel Database Without Dropping Every Table

Read article