spatie/laravel-view-models
Move complex view-prep logic out of controllers into dedicated Laravel view model classes. Extend Spatie\ViewModels\ViewModel to transform data for views, expose computed properties, and keep templates clean and focused.
Pros:
Cons:
toArray()/toJson()).make:view-model artisan command to scaffold boilerplate.toArray()) become a bottleneck for large payloads?/admin/settings).// Before
public function showDashboard() {
return view('dashboard', [
'stats' => $this->fetchStats(),
'recentActivity' => Activity::recent()->get(),
]);
}
// After
public function showDashboard(DashboardViewModel $viewModel) {
return view('dashboard', ['model' => $viewModel]);
}
make:view-model to generate boilerplate.{{ $model->stats->revenue }}
JsonSerializable or toArray() for API-friendly output:
public function toArray(): array {
return [
'id' => $this->product->id,
'name' => $this->product->name,
'price' => $this->formattedPrice,
];
}
return Inertia::render('Dashboard', [
'dashboard' => new DashboardViewModel(),
]);
$this->app->bind(DashboardViewModel::class, function () {
return new DashboardViewModel(StatsRepository::fetch());
});
composer require spatie/laravel-view-models
php artisan vendor:publish --provider="Spatie\ViewModels\ViewModelsServiceProvider"
How can I help you explore Laravel packages today?