Laravel Inertia: Simplifying Front-end Development in Laravel

Laravel Inertia

By offering a better streamlined and integrated approach to developing web applications, Inertia is a game-changer in the arena of Laravel development. For Laravel developers Inertia offers a similar workflow. Thus, it significantly reduces the learning curve – from transitioning to a front-end framework.

This seamless integration enables developers to use their existing Laravel skills and gain from Inertia’s capability to transform the front-end user experience without the need to re-architecture the web application. Thus, developers can enjoy a plethora of benefits from a unified stack to enhanced efficiency, and creating a better developer-friendly experience.

This blog focuses on the reasons for using Laravel with Inertia, its functionality, and the process of deploying this paired technology.

Why Use Inertia.js with Laravel?

Want to seamlessly integrate the latest front-end capabilities with Laravel server-side frameworks? Utilize the power of the Inertia.js tool! It offers superior enhancement to traditional server-based web applications. Its ability to develop a highly interactive user interface while maintaining the robust back-end features of Laravel makes this shared technology a popular choice among developers.

If you seek to enhance the developer’s productivity, scalability of the application, and effortless maintenance, the shared code structure between the back-end and front-end operation offered by Inertia.js with Laravel is the best solution.

How Inertia.js is Useful in Laravel Front-end Development?

Want to streamline the development process for rendering a superior user interface?

By deploying Inertia.js with Laravel, developers can easily build dynamic and reactive interfaces with front-end frameworks like React or Vue.js while maintaining server-side capabilities.

Wondering how?

Well, this shared code facilitates a single-page application experience without transitioning completely to a full-fledged SPA architecture. It thus enables developers to achieve their goals.

Additionally, Inertia uses Laravel controllers to analyze and simplify the data flow logic between the front-end and back-end. This leads to a streamlined development process because it eliminates the need to build isolated API endpoints and ensures an intelligible codebase.

How Inertia.js Works?

Inertia.js transforms the interaction between the back-end and front-end in a web application by maintaining the traditional server-based back-end architecture and rendering a seamless front-end experience.

For the shared code to deliver this superior user experience, Inertia communicates with the back-end by utilizing XHR (XMLHttpRequest) or Fetch API tool, rather than communicating outdated full-page requests. This process only transmits essential data required to complete a specific action.

Working Mechanism

Step#1

A user clicks a task, and the front-end sends a request to the server to trigger the suitable Laravel controller method.

Step#2

The Laravel controller processes the request to return a suitable Inertia response which includes the essential data for updating the web page without a complete reload.

Step#3

On the front-end, the Inertia user receives the response, utilizes this data to update the contents of the web page, and effortlessly modifies the user interface according to the obtained information.

Why Use Single Page Application Architecture?

Want to offer a highly fluid and responsive user experience through a single HTML page, and update its content as users interact with the application?

Inertia with a Single Page Application (SPA) architecture allows you to do just that!

Improved User Experience

SPA architecture offers a superior and effortless experience like a web application, reduces page reload frequency, and delivers relevant and dynamic content. Inertia balances this experience by enabling SPAs to maintain a high level of interaction while gaining from the back-end structure offered by Laravel’s framework.

Reliable Development Workflow

Inertia enables developers to smoothly transition to SPA-based architecture without the need to learn the complete front-end technology. To deliver this objective, it maintains a consistent workflow by aligning with Laravel’s structure.

Easy and Simple Development

Inertia combined with an SPA architecture eliminates the complexity of handling front-end state, routing, and API integrations. It allows developers to maintain front-end and back-end communication while enabling them to build on the SPA power.

How to Get Started with Laravel and Inertia.js?

To comprehend Inertia and the process of integrating it with Laravel, let us build a web application for a blog by utilizing Vue.js for the JavaScript front-end, Laravel for the back-end, and Tailwind CSS for styling.

Pre-requisites

You should be familiar with the following terms:

Laravel installation, database, database migration, Eloquent Models, controllers, and routing.

Vue.js basics installation, structure, and forms.

Step#1: Installing Core Elements

Create a single-page application to install core elements.

To view the homepage of the blog and a single article hosted on it, create a Blade component.

/resources/views/index.blade.php


<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>KrishaWeb Blog
  </head>
  <body>
    <header>
      <h1>Blog 1
    </header>
    <main>
      <h2>Read our latest blogs
      <section>
        <article>
          <div>
            <img src="/images/logo.png" alt="Article thumbnail" />
          </div>
          <h3>Blog title
          <p>
          </p>
          <a href="#">Read more
        </article>
      </section>
    </main>
    <footer>
      <h2>Join our Newsletter
      <input type="email" />
    </footer>
  </body>
</html>

Step#2: Setting up a Blade File

Now create a new file with a “.blade.php extension” in the Laravel project “blog/resources/views”.

Navigate to /resources/views/show.blade.php:


<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>KrishaWeb Blog
  </head>
  <body>
    <main>
      <article>
        <div>
          <img src="logo.png" alt="Article thumbnail" />
        </div>
        <h1>Blog Title
        <p>Content goes here...

</article> </main> <footer> <h2>Join our Newsletter <input type="email" /> </footer> </body> </html>

Create a new MySQL local database (titled MY_blog) and connect it to the project:”.env“:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=CW_blog
DB_USERNAME=root
DB_PASSWORD=

Run database model, migrations, and factories in Laravel application:”app/Models/Article.php“:


<?php
namespace AppModels;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    use HasFactory;
    protected $fillable = ['title', 'excerpt', 'body'];

Run database migration and export the demo articles to your database to “database/migrations/create_articles_table.php“:


<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('excerpt');
            $table->text('body');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('articles');
    }
};

Run the following code and create a new class ArticleFactory that will store our demo articles in our database.


<?php
namespace DatabaseFactories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ArticleFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => $this->faker->sentence(6),
            'excerpt' => $this->faker->paragraph(4),
            'body' => $this->faker->paragraph(15),
        ];
    }
}

That’s all we need to get started! Let’s get down to business and introduce Inertia.js to our project.

Install Inertia

The installation process of Inertia comprises two main phases: server-side (Laravel) and client-side (VueJs).

*Please Note: The official installation guide in the Inertia documentation is somewhat outdated due to Laravel 9’s default use of Vite, but the process will be covered.

Step 1: Setting Up Server-Side

To integrate InertiaJS with Laravel, the initial step involves using the terminal to install the Inertia server-side adapters through Composer. Execute the command ‘composer require inertiajs inertia-laravel’ to install the necessary package.

  • Create a root template file in Blade for Laravel 9 v9.31 that loads CSS and JS files, along with activating Vite’s functionality. Add Vite to the tags in /resources/views/app.blade.php for seamless integration with the JavaScript application.

<:!DOCTYPE html>
<:html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
  <:head>
    <:meta charset="utf-8" />
    <:meta name="viewport" content="width=device-width, initial-scale=1" />
    <:!-- Fetch project name dynamically -->
    <:title inertia>{{ config('app.name', 'Laravel') }}
    <:!-- Scripts -->
    @vite('resources/js/app.js') @inertiaHead
  
  <:body class="font-sans antialiased">
    @inertia
  <:/body>
<:/html>

Next, we will create HandleInertiaRequests middleware and publish it to our project.

We can do that by firing the below terminal command within the root directory of our project:

php artisan inertia:middleware 
  • Once this is complete, head to “App/Http/Kernel.php” and register HandleInertiaRequests as the last item in your web middleware:
'web' => [
    // ...
    App\Http\Middleware\HandleInertiaRequests::class,
],

Step 2: Setting up Client-Side

  • Next, we have to install our frontend Vue.js 3 dependencies in the same way as on the server side:

npm install @inertiajs/inertia @inertiajs/inertia-vue3
  • Next, you need to pull in Vue.js 3:
npm install vue@next
  • Update your primary JavaScript file to initialize Inertia.js with Vue.js 3, Vite, and Laravel:
 import "./bootstrap";
import "../css/app.css";
import { createApp, h } from "vue";
import { createInertiaApp } from "@inertiajs/inertia-vue3";
import { resolvePageComponent } from "laravel-vite-plugin/inertia-helpers";
createInertiaApp({
  title: (title) => `${title} - ${appName}`,
  resolve: (name) =>
    resolvePageComponent(
      `./Pages/${name}.vue`,
      import.meta.glob("./Pages/**/*.vue")
    ),
  setup({ el, app, props, plugin }) {
    return createApp({ render: () => h(app, props) })
      .use(plugin)
      .mount(el);
  },
});
  • We use Laravel’s plugin resolvePageComponent and instruct it to resolve our components from the directory ./Pages/$name.vue.
  • This is to save our Inertia components in this directory later in our project, and this plugin will assist us in automatically loading those components from the correct directory.
  • All that is left is to install vitejs/plugin-vue:

npm i @vitejs/plugin-vue
  • And update vite.config.js file:

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({
      template: {
        transformAssetUrls: {
          base: null,
          includeAbsolute: false,
        },
      },
    }),
  ],
});
  • The final step is to install our dependencies and compile our files:

npm install
npm run dev

That is it. You have a working Laravel 9 application with Vue.js 3 and Vite.

Creating Inertia Pages

  • Now we are going to create a folder called “Pages” and move your files there.
  • Then we will transform the blade component “.blade.php” to “.vue” while making the first letter of their names uppercase and turn its content into a standard Vue.js component.
  • We will move all the tags along with the components as they are already included in the main root blade component.

<:script setup>
  //
<:/script>
<:template>
  <:header>
    <:h1>CW Blog
  <:/header>
  <:main>
    <:h2>Read our latest articles
    <:section>
      <:article>
        <:div>
          <:img src="/images/CW-logo.png" alt="Article thumbnail" />
        <:/div>
        <:h3>Title for the blog
       <:p>  Article Content Goes Here.

<:a href="#">Read more <:/article> <:/section> <:/main> <:footer> <:h2>Join our Newsletter <:input type="email" /> <:/footer> <:/template>

Setting up show.vue

We’re now going to set up the “resources/js/Pages/Show.vue“ page, which is going to be the layout of our application.


<:script setup>
  //
<:/script>
<:template>
  <:header>
    <:h1>Welcome to CW Blog
  <:/header>
  <:main>
    <:article>
      <:h1>Title for the blog
      <:p>Article content goes here

<:/article> <:/main> <:footer> <:h2>Join our Newsletter <:input type="email" /> <:/footer> <:/template>

Wrapping Components

  • Create a folder named “Layouts” in “/resources/js.” In this folder, create a file named “CWLayout.vue.”
  • The file will contain separate sections for the headers and footers, with a main section designed to accommodate extra components.

This file should look like this:


<:script setup>
<:template>
    <:header>
    <:h1>CW Blog
  <:/header>
  <:main>
        <:slot />
  <:/main>
  <:footer>
    <:h2>Join our Newsletter
    <:input type="email" />
  <:/footer>
<:/template>

Creating Index.vue:

Now, we’ll import the new layout into our pages and wrap all the HTML content in it.


<:script setup>
import CWLayout from "../Layouts/CWLayout.vue";
<:/script>
<:template>
  <:CWLayout>
    <:section>
      <:h2>Read our latest articles
      <:article>
        <:div>
          <:img src="/images/CW-logo.png" alt="Article thumbnail" />
        <:/div>
        <:h3>Title for the blog
        <:p>Article content goes here!

<:a href="#">Read more <:/article> <:/section> <:/CWLayout> <:/template>

Show.vue:

Run the following script to display the layout we’ve created in the previous script.


<:script setup>
 import CWLayout from "../Layouts/CWLayout.vue";
<:/script>
<:template>
  <:CWLayout>
    <:article>
      <:h1>Title for the blog
      <:p>Article content goes here

<:/article> <:/CWLayout> <:/template>

Laravel Inertia vs Traditional Front-end Development

Laravel Inertia reduces the complexities of handling isolated codebases by combining the front-end and back-end technologies to offer a streamlined and integrated approach to the development process.

The table below outlines the differences between Laravel Inertia and Traditional Front-end Development.

AspectLaravel InertiaTraditional Front-end
Technology StackCombines Laravel back-end with front-end (Vue.js or React)Uses isolated front-end frameworks (Vue.js, React)
Rendering & RoutingServer-managed routing for client-side renderingClient-managed routing with server-side rendering
Development SpeedReduces context switching to enhance development speedMay frequently need context-switch between back-end and front-end
API Requests & Data FetchingAPI requests are rendered with shareable Laravel routesAPI requests and data fetching are handled manually
Template Engine IntegrationIntegrates with Blade for server-rendered templatesDepends on templating engines like EJS & Handlebars
State ManagementUses server-driven state to simplify state management usingManual state management with tools like Redux
SEO & Page Load PerformanceServer-side rendering offers enhanced SEOAdditional configurations required by SEO
Code Simplicity & ReadabilityPromotes simpler code structure and better readabilityMight involve complex code separation and management
TestingEasier testing due to seamless back-end/front-end integrationSeparate testing environments for back-end and front-end
Maintenance & UpdatesA unified codebase offers simplified maintenanceUpdates require back-end and front-end codes to be synchronized
Ecosystem & Community SupportThe Laravel ecosystem has a growing community supportFront-end frameworks have established communities
Learning CurveDevelopers familiar with Laravel have a reduced learning curveDevelopers need proficiency in different front-end frameworks

Conclusion

Laravel Inertia easily handles the traditional challenge of creating dynamic, simpler, and responsive web applications by streamlining the workflow process between the back-end and front-end. As Inertia seamlessly integrates with Laravel it offers advantages in development speed, simplified code structure, and maintenance. Additionally, it streamlines testing and state management leading to an efficient and unified front-end development experience as compared to the traditional approach.

Do you still need more reasons to make the switch?

author
Nirav Panchal
Lead – Custom Development

Lead of the Custom Development team at KrishaWeb, holds AWS certification and excels as a Team Leader. Renowned for his expertise in Laravel and React development. With expertise in cloud solutions, he leads with innovation and technical excellence.

author

Recent Articles

Browse some of our latest articles...

Prev
Next