InertiaJS data evaluation in Laravel and VueJS applications

Constantin Druc · 20 Feb, 2021

Laravel debugbar package: https://github.com/barryvdh/laravel-debugbar

There are three different ways we can pass data to our InertiaJS responses.

1. By assigning the values directly - values are always evaluated regardless of whether we are dealing with a first page load or a partial request.

1public function create(): Response
2{
3 return Inertia::render('CreateJob', [
4 'mechanics' => User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get(),
5 'consultants' => User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get(),
6 ]);
7}

2. By wrapping and returning the values inside a closure - values are evaluated on first page loads and optionally on partial requests using the only key of the inertia request options.

1public function create(): Response
2{
3 return Inertia::render('CreateJob', [
4 'mechanics' => function () {
5 return User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get();
6 },
7 'consultants' => function () {
8 return User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get();
9 },
10 ]);
11}

3. By using Inertia's lazy method - values are never evaluated on first page loads but only optionally, on partial requests using the only key of the inertia request options.

1public function create(): Response
2{
3 return Inertia::render('CreateJob', [
4 'mechanics' => Inertia::lazy(function () {
5 return User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get();
6 }),
7 'consultants' => Inertia::lazy(function () {
8 return User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get();
9 })
10 ]);
11}

Here are all versions again:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Models\User;
6use Inertia\Inertia;
7use Inertia\Response;
8 
9class JobsController extends Controller
10{
11 public function create(): Response
12 {
13 return Inertia::render('CreateJob', [
14 // always executed
15 'mechanics' => User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get(),
16 'consultants' => User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get(),
17 
18 // executed on first load and partial requests when asked for
19 'mechanics' => function () {
20 return User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get();
21 },
22 'consultants' => function () {
23 return User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get();
24 },
25 
26 // only on partial requests when asked for
27 'mechanics' => Inertia::lazy(function () {
28 return User::where('type', 'mechanic')->filter(request()->only('term'))->limit(15)->get();
29 }),
30 'consultants' => Inertia::lazy(function () {
31 return User::where('type', 'consultant')->filter(request()->only('term'))->limit(15)->get();
32 })
33 ]);
34 }
35}