Vue Laravel CRUD Example With Vue Router & Sweet Alert

In this tutorial i am going to create Laravel and Vue js crud tutorial. We will create a Single Page Application(SPA) using the Laravel and Vue.js. This tutorial you will learn how to use vue router and v-form package to create laravel vue js crud. 

In Todays, Most popular JS Framework are Angular JS and Vue JS. Angular JS and Vue JS are a very user friendly JS Framework and most popular. It provides to manage whole project or application without refresh page and powerful jquery validation.

In this post i going to lean how to create CRUD(Create, Read, Update and Delete) application with pagination using Laravel 6. In this example i added "User Management" with you can do several option like as bellow: 

1. User Listing

2. User Create

3. User Edit

4. User Delete

I will show you how to use JavaScript moment js and how to use Vue filter, Vue progressbar, Vue router to complete this single page application.

you can implement crud application from scratch, so no worry if you can implement through bellow simple step. After create successful example, you will find layout as bellow:

Preview: User Table

laravel-vue-js-crud-preview-1.jpeg

Preview: Add User Modal

laravel-vue-js-crud-preview-2.jpeg

Preview: Error message before submit non-validate data

laravel-vue-js-crud-preview-3

Preview: Edit modal window

laravel-vue-js-crud-preview-4

Now let's start laravel vue js crud application tutorial from scratch.

 

Step 1: Laravel Installation

In first step, If you haven't installed Laravel in your system then you have to run bellow command and get fresh Laravel project.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create items table and model

In this step i will use User model and users table to create vue js laravel crup single page application. So paste this below code to your users table.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
   
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('type')->default('user');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

After create "usres" table you should create Item model for items, so first create file in this path app/User.php and put bellow content in user.php file:

app/User.php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [];

}

Now run migration command after setup your database. 

Step 3: Define the API routes

Now, we need to define the API routes inside the routes >> api.php file.

routes/api.php

//Vue js Api Route

Route::apiResources(
	[
		'user' => 'API\UserController'
	]
);

Step 4: Create Controller

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/UserController --api

Ok, now we have created new controller as UserController in this path app/Http/Controllers/API/UserController.php. this controller will manage all route method:

Step 5 : Setup Laravel Mix

Now open webpack.mix.js which is located inside your root directory.

webpack.mix.js

mix.js('resources/assets/js/app.js', 'public/js/app.js')
   .sass('resources/assets/sass/app.scss', 'public/css/app.css')
   .version();

Step 6 : Install Vue dependency and edit configurations

Now, go inside the project folder and install the frontend dependencies using the following command.

Read also : User Roles and Permissions Tutorial in Laravel without Packages

npm install

Now run following command, you can visit vue official documentation

npm install vue-router

Now we are going to install vue-progressbar. We will use it when a user created then progressbar will be shown in top of our application. Now run following command, you can visit vue progressbar official documentation

npm install vue-progressbar

Now we have to install moment js in our app to format date like laravel carbon function. You can visit moment js official documentation

npm install moment --save

Now we have to install v-form for client side validation. Read their documentation to learn more how to use it and how v-form works.

npm i axios vform

Now last is sweet alert 2. Now run below command to install it. You can visit sweet alert 2 official documentationNow run command to compile our all javascript file.

npm install watch

Now create folder and file like below image.

laravel-vue-js-crud.jpeg

Step 7: Setup js file

resources/assets/js/app.js

Read also : Laravel 6 Ajax Form Submit With jQuery Validation

require('./bootstrap');

window.Vue = require('vue');

//Import Vue Filter
require('./filter'); 

//Import progressbar
require('./progressbar'); 

//Setup custom events 
require('./customEvents'); 

//Import View Router
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//Import Sweetalert2
import Swal from 'sweetalert2'
window.Swal = Swal
const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000,
  timerProgressBar: true,
  onOpen: (toast) => {
    toast.addEventListener('mouseenter', Swal.stopTimer)
    toast.addEventListener('mouseleave', Swal.resumeTimer)
  }
})
window.Toast = Toast

//Import v-from
import { Form, HasError, AlertError } from 'vform'
window.Form = Form;
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)

//Routes
import { routes } from './routes';

//Register Routes
const router = new VueRouter({
    routes, 
    mode: 'hash',

})

//Vue.component('example-component', require('./components/ExampleComponent.vue').default);

const app = new Vue({
    el: '#app',
    router
});

resources/assets/js/customEvents.js

This is our custom events generator code. You can see its documentation to know better. 

//Setup our custom events in vue

let Fire = new Vue()
window.Fire = Fire;

 

resources/assets/js/filter.js

//Vue Filter to make first letter Capital
Vue.filter("strToUpper", function(text) {

	return text.charAt(0).toUpperCase() + text.slice(1);

});

//Vue moment js to show human readable date
import moment from "moment"; //Import Moment

Vue.filter("formatDate", function(date) {

	return moment(date).format('MMMM Do YYYY');

}); 

resources/assets/js/progressbar.js

import VueProgressBar from 'vue-progressbar';

Vue.use(VueProgressBar, {
  color: 'rgb(143, 255, 199)',
  failedColor: 'red',
  height: '4px',
  transition: {
    speed: '0.4s',
    opacity: '0.6s',
    termination: 300
  },
})

resources/assets/js/routes.js

import Dashboard from './components/admin/DashboardComponent.vue'
import Profile from './components/admin/ProfileComponent.vue'
import User from './components/admin/UserComponent.vue'

export const routes = [
    {
        path:'/dashboard',
        component:Dashboard
    },
    {
        path:'/profile',
        component:Profile
    },
    { 
        path:'/users',
        component:User
    },
 
 
];

Step 8 :  Setup Controller

App\Http\Controllers\API\UserController.php


namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    
    public function index()
    {
        return User::latest()->get();
    }

    public function store(Request $request)
    {   
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'type' => 'required',
        ]);

        return User::create([
           'name' => $request['name'],
           'email' => $request['email'],
           'password' => \Hash::make($request['password']),
           'type' => $request['type'],
        ]);
    }

    public function show($id)
    {
        //
    }

    public function update(Request $request, $id)
    {   
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'type' => 'required',
        ]);

        $user = User::findOrFail($id);

        $user->update($request->all());
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return response()->json([
         'message' => 'User deleted successfully'
        ]);
    }
}

Step 9: Create Blade File

In this step we have to create only one blade file that will manage create, update and delete operation of items module with vue js.In this file i added jquery, bootstrap js and css, vue.js, vue-resource.min.js, toastr js and css for notification in this blade file.

resources/views/master.blade.php

resources/assets/js/components/admin/UserComponent.vue

Now every thing is done. Now you are ready to check it. Hope it will help you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website