Laravel Inertia: Installation Tutorial and Tips & Tricks

Quick Summary:

Ever heard of Laravel Inertia, but not sure what it helps with? Are you looking for a way to optimize Laravel app performance by improving its integration with modern frontend frameworks? This Laravel Inertia js tutorial will walk you through the tips and tricks to install and utilize Laravel Inertia for building modern SPAs that are scalable, secure, and performance-oriented.

Laravel is one of the best PHP frameworks for developing responsive and modern web apps. It can be integrated with most modern frontend frameworks like Vue, React, Svelte, and more for developing a full-stack modern web app. Using Laravel Inertia efficiently establishes a link between the client-side framework (Laravel) and the frontend framework (Vue/React/Svelte). To better understand how Laravel Inertia works and how it benefits your overall Laravel project, we should start by understanding what Inertia is.

What is Inertia.js in Laravel?

Inertia is a JavaScript-based routing library popularly used for developing modern Single Page Apps by leveraging classic server-side routing and controllers. It can be considered a ‘glue’ that tightly couples the back and frontend of a modern web app.

What is InertiaJS

Developers can use Inertia to couple powerful backend frameworks like Laravel/Rails with powerful frontend frameworks like Vue/React/Svelte. So, it is not a Laravel-specific or Vue.js-specific package, as some developers wrongly assume. Instead, it offers adapters for all the mentioned frameworks on the frontend and back end.

Laravel Inertia js allows Developers to use traditional development methods like…

  • Traditional Routing
  • Traditional Controller
  • Authentication & Authorization
  • Middleware

…for developing modern monolith SPAs, without having to use complex modern web development tools such as:

  • APIs
  • OAuth

How does Inertia JS work?

When you use Inertia to power your Laravel-based web app, you get to use Laravel’s existing provisions for middleware, controllers, routing, authorization, authentication, and more. The difference is noted in the view layer. Generally, you would use server-side rendering using ERB or Blade templates. Inertia replaces that with JavaScript page components. Why’s that better? Now you can design and build the front end using modern web app frameworks like Vue, React, and Svelte.

How does InertiaJS work

Now we have a modern-looking SPA with a powerful backend framework like Laravel. However, this still doesn’t provide a true single-page application experience or benefit. If a user clicks on any link, the browser would still make a full-page visit, leading to the client-side framework entirely rebooting when the page loads.

However, Inertia is essentially a client-side routing library, allowing users to make page visits without forcing a full page to reload. This is done using the <Link> component. When a user clicks an ‘inertia link,’ Inertia intercepts it and makes an AJAX request to the server. The server identifies it as an Inertia visit and returns a JSON response with a JavaScript page component name and props instead of a full HTML response. It dynamically swaps the current page component with the new updated one, updating the history state. Doing so greatly increases the web app loading speed as it requires loading all the basic assets only once without having to refresh the CSS, header & footer, scripts, and other elements for every page request.

Also Read: Laravel Best Practices 2024

Laravel Inertia Tutorial

Setting up Inertia in your Laravel-based app is a seamless experience; all credit to the excellent Inertia team, who have provided detailed and easy-to-follow official Laravel documentation with all installation codes and its purpose to guide you through the process. We will break it down further here for your reference.

The entire Laravel Inertia js tutorial can be divided into four essential phases:

  1. Setting up the server-side with Laravel
  2. Setting up the middleware
  3. Setting up Client Side with Vue/React/Svelte
  4. Compile your Project with Laravel Mix

Laravel Inertia Setup Phase 1 – Setting up the server-side with Laravel

It is ideal first to set up the backend of your modern web app. Though you can use Rails/Laravel to power the backend, for our reference, we will be using Laravel for this tutorial.

Create a demo Laravel project

Open your preferred code editor platform and create a new demo Laravel project by inserting this syntax:

composer create-project --prefer-dist laravel/laravel inertia-vue

Install Dependencies

composer require inertiajs/inertia-laravel

Next, install the server-side Laravel adapters from Inertia’s official documentation page.

Setup Root Template

Next, search for the welcome.blade.php file under the Resources/Views Folder in your project folder. Rename this folder to ‘app.blade.php.’

After doing this, replace the content of the app.blade.php page with this code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
    <script src="{{ mix('/js/app.js') }}" defer></script>
  </head>
  <body>
    @inertia
  </body>
</html>

Here the ‘@inertia’ directive acts like a helper that is a convenient way of passing first content to inertia and telling Laravel that the views are being generated using Inertia.

“Are you looking to hire LARAVEL Developers?”

Find the best full-stack Laravel Developers in India to start your web development project within 48 hours

Laravel Inertia Setup Phase 2 – Setting up Middleware

Now that we have the Laravel Inertia js server-side setup, the next step is to create the middleware. Go to the middleware section of the Inertia documentation and copy the following code and run it on the editor:

php artisan inertia:middleware

Running this code will create a new 'HandleInertiaRequest.php' file under your project’s Middleware folder in the App Directory.

Next, go to the App/HTTP/Kernel subdirectory under Middleware, and add this code as the last item in the web middleware group:

HandleInertiaRequests::class

Laravel Inertia Setup Phase 3 – Setting up Client-Side with Vue 3

Now we have the server-side and middleware framework configured. Next, we need to work on the client-side framework. With Inertia, you can integrate three of the leading frontend JavaScript frameworks with your Laravel Project:

  • Laravel Inertia Vue
  • Laravel Inertia React
  • Laravel Inertia Svelte

This tutorial will focus on Laravel Inertia Vue 3 integration, as it is one of the most common and popular pairs often used for most projects.

Install Dependencies

npm install @inertiajs/inertia @inertiajs/inertia-vue3

yarn add @inertiajs/inertia @inertiajs/inertia-vue

Initializing App

Now you need to update the main JavaScript file for booting the Inertia app. This will initialize the client-side framework with the base Inertia component:

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

createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

Notice in the above code that there is a callback function named resolve. This callback tells Inertia how to load a page component. It receives a string and returns a page component. Here we can also observe that we are asking resolve to look in a ‘Pages’ directory for tracking the current page component. For this, we need to create a subfolder named ‘Pages’ under the JS subfolder of Resources.

Laravel Inertia Phase 4 – Compile your Project with Laravel Mix

Next, go to the webpack.mix.js file, and under mix.js(‘resources/js/app.js,’ public/js’), type the Vue version you want to work with:

.vue(3)

Then on the last line, enter this code:

.version();

Next, type the following command for compiling your project

npx mix

Your Laravel Inertia project is now ready to be deployed.

What challenges Laravel Inertia helps tackle

Laravel Inertia is a useful combination that can help developers solve the following complexities:

Challenges Laravel Inertia helps to tackle

Complexities of Single Page Application

Inertia helps reduce the complexities of building modern SPAs by allowing developers to use traditional routing, navigation, authentication, authorization, and more methods.

Browser Problems

Inertia has in-built provisions and services that help solve most browser issues that generally come up when dealing with SPAs. These problems include loading indication, browser history management, scroll position, asset reloading and versioning, and more.

Security Challenges

If you build an API-powered SPA, you need to integrate CORS support for accessing resources available on other origins. Inertia eliminates this need as your app gets its data through controllers and is housed in the same domain as the app’s JS components. In addition, with Laravel Inertia authentication, developers can set up authorization on the server-side and conduct security checks by passing tokens as props to the page component.

Benefits and Challenges of using Laravel Inertia

With everything in mind, Laravel Inertia is a concept worth understanding and utilizing in your Laravel-based project. However, no technology or framework comes without any challenges or limitations. Therefore, before choosing Laravel Inertia for your project, here are the pros and cons.

Benefits of using Laravel Inertia js

  • Inertia helps eliminate the complexity of client-side routing
  • It can be easily configured with modern frontend frameworks like Vue, React, and Svelte
  • All application paths are contained in a single file

Benefits of using Laravel Inertia

Limitations of using Laravel Inertia js

  • The developer working on this project needs in-depth knowledge about PHP and JS technology they choose
  • Its usability is limited without Vuex
  • Backend API needs to be recreated if Laravel Inertia is used for creating an iOS/Android app

Limitations of using Laravel Inertia

Also Read: Laravel Security Best Practices

Final Words

This is your go-to Laravel Inertia tutorial and best tips and tricks guide. Make sure to go through the official Inertia documentation for troubleshooting and understand the benefits and limitations of Inertia before integrating it into your Laravel project.

FAQs

1. What is Inertia Framework?

Inertia is a new method of building modern SPAs using classic server driven web apps. It allows developers to develop fully client side rendered, SPAs without needing to call any API or handling other complexities of modern app development.

2. Why do we use Inertia?

Inertia allows a seamless integration between the backend (Rails, Laravel) and modern frontend frameworks (React, Vue, Svelte) with many added benefits for security, app development time, client-side routing and more.

3. How does Inertia JS work?

Inertia at its core is a client-side routing library. It works via adapters that are available on its official website for backend technologies such as Rails and Laravel and frontend technologies like Vue3, Vue 2, React and Svelte.

have a unique app Idea?

Hire Certified Developers To Build Robust Feature, Rich App And Websites

Need Consultation?

Put down your query here...

    Saurabh Barot

    Saurabh Barot, the CTO of Aglowid IT Solutions, leads a team of 50+ IT experts across various domains. He excels in web, mobile, IoT, AI/ML, and emerging tech. Saurabh's technical prowess is underscored by his contributions to Agile, Scrum, and Sprint-based milestones. His guidance as a CTO ensures remote teams achieve project success with precision and technical excellence.

    Related Posts