Writing

Laravel ViewModel: A Smarter Way to Handle View Data

Sep 2024 · 4 min read


A controller action often ends up gathering data from three or four places just to render one page. The view gets a long list of variables, the controller gets fat, and the same query logic starts to repeat in other actions. A ViewModel fixes this by moving all of that preparation into one small class.

A ViewModel is a plain PHP class with one job: take what the page needs, shape it, and hand it to the view. Nothing more.

The ViewModel class

app/ViewModels/DashboardViewModel.php

<?php

namespace App\ViewModels;

use App\Models\Order;
use App\Models\User;

class DashboardViewModel
{
    public function __construct(private User $user) {}

    public function toArray(): array
    {
        return [
            'name'        => $this->user->name,
            'ordersCount' => Order::where('user_id', $this->user->id)->count(),
            'lastOrder'   => Order::where('user_id', $this->user->id)
                ->latest()
                ->first(),
        ];
    }
}

The controller stays thin

app/Http/Controllers/DashboardController.php

<?php

namespace App\Http\Controllers;

use App\ViewModels\DashboardViewModel;

class DashboardController extends Controller
{
    public function __invoke()
    {
        $vm = new DashboardViewModel(auth()->user());

        return view('dashboard', $vm->toArray());
    }
}

In Blade you simply use the keys the ViewModel returned, like {{ $ordersCount }} or {{ $lastOrder->total }}.

Why it helps

The controller only decides which page to show. The ViewModel decides what the page shows. That class is easy to unit test, easy to reuse in another controller or an API endpoint, and your Blade templates stay free of query logic. Next time a view needs data from several sources, give it its own ViewModel instead of growing the controller.