Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

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
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
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
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 →
JSON Alexander Gives Developers a Simpler, More Trustworthy Way to View JSON in the Browser image

JSON Alexander Gives Developers a Simpler, More Trustworthy Way to View JSON in the Browser

Read article
Manage Software Licenses in Laravel with Laravel Licensing image

Manage Software Licenses in Laravel with Laravel Licensing

Read article
Matt Stauffer Joins the PHP Foundation Board — What It Means for Laravel image

Matt Stauffer Joins the PHP Foundation Board — What It Means for Laravel

Read article
Log User Activity in Your Laravel App with Activity Log v5  image

Log User Activity in Your Laravel App with Activity Log v5

Read article
Manage Laravel Cloud from the Terminal with the New Cloud CLI image

Manage Laravel Cloud from the Terminal with the New Cloud CLI

Read article
UnitTest Attribute and More in Laravel 13.3.0 image

UnitTest Attribute and More in Laravel 13.3.0

Read article