Polyscope - The agent-first dev environment for Laravel

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
Acquaint Softtech

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

Visit Acquaint Softtech
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
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
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
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
Lucky Media logo

Lucky Media

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

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

Tinkerwell

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

Tinkerwell
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 →
Storage Cache Store in Laravel 13.10.0 image

Storage Cache Store in Laravel 13.10.0

Read article
Laravel MongoDB Full-Text Search tutorial: The Art of the Relevancy image

Laravel MongoDB Full-Text Search tutorial: The Art of the Relevancy

Read article
Drag-and-Drop Sorting for Eloquent Models with Reorderable for Laravel image

Drag-and-Drop Sorting for Eloquent Models with Reorderable for Laravel

Read article
Ship AI with Laravel: Real-Time Streaming Chat UI with Livewire image

Ship AI with Laravel: Real-Time Streaming Chat UI with Livewire

Read article
Frontend Nation 2026 Returns June 3-4 with Laravel in the Lineup image

Frontend Nation 2026 Returns June 3-4 with Laravel in the Lineup

Read article
Use a Google Sheet as Your Laravel Database with the Google Sheets Database Driver image

Use a Google Sheet as Your Laravel Database with the Google Sheets Database Driver

Read article