Outsource Laravel Development Partner - $3200/Month | Bacancy

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
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
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 →
Improved Skill and Guideline Detection in Laravel Boost v2.2.0 image

Improved Skill and Guideline Detection in Laravel Boost v2.2.0

Read article
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article