Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

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

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

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

Shift
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
Lucky Media logo

Lucky Media

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

Lucky Media
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 →
Statamic 6 Is Officially Released image

Statamic 6 Is Officially Released

Read article
Livewire 4 and Blade Improvements in Laravel VS Code Extension v1.5.0 image

Livewire 4 and Blade Improvements in Laravel VS Code Extension v1.5.0

Read article
Manage PostgreSQL Databases Directly in VS Code with Microsoft's Extension image

Manage PostgreSQL Databases Directly in VS Code with Microsoft's Extension

Read article
NativePHP for Mobile Is Now Free image

NativePHP for Mobile Is Now Free

Read article
Fuse for Laravel: A Circuit Breaker Package for Queue Jobs image

Fuse for Laravel: A Circuit Breaker Package for Queue Jobs

Read article
Generate Complete Application Modules with a Single Command using Laravel TurboMaker image

Generate Complete Application Modules with a Single Command using Laravel TurboMaker

Read article