We noticed you're using an ad blocker

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Laravel Inertia Js CRUD tutorial

world cup 2022

FootballDesk

Get update standing EPL, UEFA, LaLiga and more

Get Now

Inertia Js is a different approach to make a SPA (Single Page Application). It's not a framework or not a replacement of another method which already exists. The beauty of the Inertia Js is we don't need to maintain sperate API routes for fetching data, it automatically passes the server-side return data into client-side as vue props. It'll be more clear when we'll create a simple CRUD application with Laravel Inertia Js. If you are interested to learn how to make a Laravel Inertia CRUD application then this step by step tutorial for you to learn Laravel Inertia js CRUD operation by making a simple CRUD application. The Inertia Js officially supports React, VueJs, Svelte with backend Laravel, Rails. Here we'll work with Laravel and VueJs.

 

Table of Contents

  1. Install Laravel
  2. Install Laravel UI
  3. Install Laravel Inertia
  4. Define a resource route
  5. Make a Model
  6. Make a controller for CRUD operation
  7. Make view for CRUD

 

Step 01: Install Laravel

Install a fresh instance of the Laravel framework. Here I am installing Laravel 7, you can also work with Laravel 6.

composer create-project laravel/laravel laravel-inertia-crud

 

Step 02: Install Laravel UI

From Laravel 6 the UI scaffolding removed to a separate Laravel official package called laravel/ui. We have to install it.

composer require laravel/ui

run this command for auth scaffolding with vue presets.

php artisan ui vue --auth

now run this command for installing npm dependencies & compiling assets.

npm install && npm run dev

 

Step 03: Install Laravel Inertia

Run this composer command for installing Laravel Inertia package.

composer require inertiajs/inertia-laravel

Now make an app.blade.php file inside the resources/views directory.

<!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="" rel="stylesheet"/>
    <script src="" defer></script>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h2 class="app-title">Laravel Inertia Js CRUD</h2>
        </div>
    </div>
</div>
<hr>
<div class="container">
    <div class="row">
        @inertia
    </div>
</div>

</body>
</html>

Note: Here you can see we just added inertia directive @inertia only and all the other things are the same as usual.

 

install inertia & inertia vue with npm command

npm install @inertiajs/inertia @inertiajs/inertia-vue

 

Now copy these code and paste into the resources/js/app.js file.

require('./bootstrap');

import { InertiaApp } from '@inertiajs/inertia-vue'
import Vue from 'vue'

Vue.use(InertiaApp)

const app = document.getElementById('app')

new Vue({
    render: h => h(InertiaApp, {
        props: {
            initialPage: JSON.parse(app.dataset.page),
            resolveComponent: name => require(`./Pages/${name}`).default,
        },
    }),
}).$mount(app)

 

Note: Our Laravel Inertia Js setup finished. Now open the command prompt and run this command for watching file changes and auto compilation.

npm run watch

 

Step 04: Define a resource route

Route::resource('admin/contacts', 'ContactController');

 

Step 05: Make a Model

Make a model contact model for our CRUD application. In this model, we have declared public $timestamps = false because in our table created_at and updated_at fields not exists.

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    public $timestamps = false;
    protected $guarded = [];
}

 

Step 06: Make a controller for CRUD operation

Make a Contact controller for our entire contact CRUD operation. The cool part is we don't need to make separate route and controller for AJAX data fetch, insert and update and delete operation. In this controller, we'll do like as normal vanilla Laravel CRUD operation. The magical part will take care of by Inertia.

<?php namespace App\Http\Controllers;

use App\Contact;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ContactController extends Controller
{
    
    public function index()
    {
        $data = Contact::all();
        return Inertia::render('contacts/index', ['data' => $data]);
    }
    
    public function store(Request $request)
    {
        Contact::create($request->all());
        return redirect()->back();
    }

    public function update(Request $request)
    {
        if ($request->has('id')) {
            Contact::find($request->input('id'))->update($request->all());
            return redirect()->back();
        }
    }

    public function destroy(Request $request)
    {
        if ($request->has('id')) {
            Contact::find($request->input('id'))->delete();
            return redirect()->back();
        }
    }
} 

Note: Look at the code, everything as usual except we just use Inertia render method inside the index method. According to our render method, the inertia will find a view inside resources/js/Pages/contacts/index . Now we have to create that file as a normal vue component.

 

Step 07: Make view for CRUD

Now make an index.vue file inside the resources/js/Pages/contacts directory with these codes.

<template>

    <div class="col-md-6">
        <button class="btn btn-sm btn-primary" @click="openModal()">Add New</button>
        <table class="table table-bordered table-condensed">
            <thead>
            <tr>
                <td>Name</td>
                <td>Phone</td>
                <td>Action</td>
            </tr>
            </thead>
            <tr v-for="row in data">
                <td></td>
                <td></td>
                <td width="130">
                    <button @click="edit(row)" class="btn btn-sm btn-primary">Edit</button>
                    <button @click="deleteRow(row)" class="btn btn-sm btn-danger">Del</button>
                </td>
            </tr>
        </table>

        <div class="modal fade" id="modal">
            <div class="modal-dialog">

                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">New Contact</h4>
                    </div>
                    <div class="modal-body">

                        <div class="form-group">
                            <label for="name">Name</label>
                            <input class="form-control" required id="name" v-model="form.name"/>
                        </div>
                        <div class="form-group">
                            <label for="phone">Phone</label>
                            <input class="form-control" required id="phone" v-model="form.phone"/>
                        </div>


                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" @click="closeModal()">Close</button>
                        <button type="submit" class="btn btn-primary" v-show="!editMode" @click="save(form)">Save
                        </button>
                        <button type="submit" class="btn btn-primary" v-show="editMode" @click="update(form)">Update
                        </button>
                    </div>
                </div><!-- /.modal-content -->

            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

    </div>


</template>

<script>
    export default {
        props: ['data'],
        data() {
            return {
                editMode: false,
                form: {
                    name: null,
                    phone: null,
                },
            }
        },
        methods: {
            openModal: function () {
                $('#modal').modal('show')
            },
            closeModal: function () {
                $('#modal').modal('hide')
                this.reset();
                this.editMode=false;
            },
            reset: function () {
                this.form = {
                    name: null,
                    phone: null,
                }
            },
            save: function (data) {
                this.$inertia.post('/admin/contacts', data)
                this.reset();
                this.closeModal();
                this.editMode = false;
            },
            edit: function (data) {
                this.form = Object.assign({}, data);
                this.editMode = true;
                this.openModal();
            },
            update: function (data) {
                if (!confirm('Sure')) return;
                data._method = 'PUT';
                this.$inertia.post('/admin/contacts/' + data.id, data)
                this.reset();
                this.closeModal();
            },
            deleteRow: function (data) {
                if (!confirm('Sure')) return;
                data._method = 'DELETE';
                this.$inertia.post('/admin/contacts/' + data.id, data)
                this.reset();
                this.closeModal();
            }
        }
    }
</script>

 

Our Laravel Inertia js CRUD application is ready to use. Now open another command prompt and run php artisan serve and browse.

http://localhost:8000/admin/contacts

 

I have tried my best to make this post easy & clear with step by step process for Laravel Inertia Js CRUD application. If this post helpful to you then please share it with others.


Share on




Related Post - Latest Post


Tinkerpad - A minimal Laravel code editor

Laravel Ajax Datatable CRUD

Laravel 8 CRUD example - Step by step

Laravel 7 CRUD tutorial

Laravel Livewire CRUD tutorial

Laravel 6 jQuery Ajax CRUD tutorial