How to set up and use Inertia in Laravel

Introduction

Traditionally MVC (Model View Controller) has been the norm where PHP code is processed with data passed into views and then the whole HTML page is sent back to the browser. The popularity of JavaScript frameworks and libraries such as React, Vue.js, and Angular introduced the separation of backend and frontend with PHP serving as an API that returns data to the JavaScript framework.

Inertia brings back the same MVC model except it integrates those same modern Javascript frameworks to be used with PHP code. Inertia was mainly created for Laravel so it can only be paired with that PHP framework however they do now support Ruby on Rails and the Pheonix framework.

At the time of writing this guide, Inertia can be set up to work with the following Javascript frameworks.

  • Vue 2
  • Vue 3
  • React
  • Svelte

site-2.png

How to set up Inertia

Install package

This guide will act as if a new Laravel project is created so that everything required to get Inertia running is detailed.

Also, keep in mind this setup is using version 11 of Laravel so there may be differences when using version 10 or below. Another thing to consider is the Javascript build tool as Vite will be used rather than Laravel mix as again Vite is now the default for new apps.

Start by creating a new Laravel app using the command below or using an existing one.

composer create-project laravel/laravel inertia-app

Change the current directory into the app.

cd inertia-app

Now add the inertia composer package.

composer require inertiajs/inertia-laravel

Layout

Go to the resources/views folder and create a new file named app.blade.php with the following content.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
        @vite('resources/js/app.js')
        @inertiaHead
    </head>
    <body>
        @inertia
    </body>
</html>

Middleware

A middleware is required for inertia, run the following command to add it

php artisan inertia:middleware

Go to the bootstrap folder and open the app.php file, and add a use statement for the HandleInertiaRequests class.

use App\Http\Middleware\HandleInertiaRequests;

Within the withMiddleware function add the new middleware.

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        HandleInertiaRequests::class,
    ]);
})

The $rootView variable will point to the resources/views so the variable has to match up to the path of the app.blade.php that was created.

protected $rootView = 'app';

If the app.blade.php were located inside the path resources/views/layouts then the $rootView variable would be set to the following.

protected $rootView = 'layouts/app';

For this guide stick to ‘app’ rather than ‘layouts/app’ for the rootView variable.

Node package manager

Now to set up the clientside part of the library, this guide will use Vue as it’s the most popular Javascript framework for Laravel developers.

Use npm to install the inertia vue3 package.

npm install @inertiajs/vue3

If Vue is not already installed then it needs to be with the following.

npm install vue@latest

This command is also required so Vue can be used inside the Vite build tool.

npm install @vitejs/plugin-vue

Open the vite.config.js inside of the project folder and copy and paste the following config code. This will initialize Vue and call the app.js file which will have the Inertia function call code.

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [
    laravel({
      input: ['resources/css/app.css', 'resources/js/app.js'],
      refresh: true,
    }),
    vue(),
  ],
  resolve: {
    alias: {
      '@': '/resources/js',
    },
  },
});

Go to the app.js file inside the resources/js directory and add in the below code which uses Inertia to load the vue files located inside of the resources/js/Pages directory.

import './bootstrap';

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
  resolve: name => {
    const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
    return pages[`./Pages/${name}.vue`]
  },
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

That completes the setup up and you are now in a position to start creating Vue pages, the next section will cover how to do this.

Create a test page

Now we want to see inertia working so we can verify that the above setup is working.

Start by using the terminal to create a new controller class.

 php artisan make:controller TestController

Open the TestController.php file located inside the app/Http/Controllers directory and add the below method.

The show method will render a Vue component with a list of fast food places passed in as a variable.

<?php

namespace App\Http\Controllers;

use Inertia\Inertia;

class TestController extends Controller
{
    public function show()
    {
        return Inertia::render('Test', [
            'fastFoods' => [
                'McDonalds',
                'Burger King',
                'KFC',
                'Subway',
                'Pizza Hut'
            ]
        ]);
    }
}

The new controller needs a new route, open the web.php inside of the routes folder and include the full namespace to the TestController.

use App\Http\Controllers\TestController;

Add the new route with the URL /test routing to the TestController show method.

Route::get('/test', [TestController::class, 'show']);

The Vue component referenced in the controller needs to be added.

<script setup>
  defineProps({ fastFoods: Array })
</script>
 
<template>
  <div v-if="fastFoods && fastFoods.length > 0">
    <h1>Fastfoods</h1>
    <ul>
      <li v-for="fastFood in fastFoods">{{ fastFood }}</li>
    </ul>
  </div>
</template>

Start up the Laravel app by using the artisan serve command.

php artisan serve

Vite needs to run so the Vue components will load, use NPM to run it.

npm run dev

Go to the URL http://localhost:8000/test and you should see the list of fast food restaurants as a bullet point list.

test-page.png

Conclusion

After following this guide you will be in a prime position to start developing Laravel apps with Inertia that use modern Javascript frameworks/libraries such as React, Vue.js, and Svelte.

Inertia makes it easier to integrate the backend system with the frontend system without worrying about implementing complex authentication and creating an API to connect two separate applications.

A popular stack used today is the VILT (Vue Inertia Laravel TailwindCSS) and I would recommend that stack if you want to develop your skills and experience.