How to Create CRUD Operation on Laravel 8 with Vue JS ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Laravel Vue js CRUD example

Today now in this article i will show you Laravel Vue js CRUD example. Here we will see and also know about how to build Create, Read, Update, and Delete API and then we will know how to consume an APIs to perform CRUD operations in Laravel and Vue JS application.

We are know that for the software engineer create, read, update, and delete are not just any simple words. Those are the foundational building block for every application as like creating, reading, updating, and deleting the data. We know that all the terminology must be different sometimes, for such as , retrieval rather than read, modify some times of the update, or destroy is the alternately of delete.

Laravel 8 Vue JS CRUD
  • Create a Laravel new Project
  • database connection with Project
  • Create a new model and run migration
  • Create and configure the the controller
  • Add new routes
  • Install Laravel Vue UI
  • Install all NPM dependencies
  • Build Vue Js CRUD Components
  • Test Laravel Vue JS CRUD operations

So let’s start with a new example of creating Laravel Vue Js CRUD application.

Read Also: How to Http Curl Delete Request in Laravel?

Install Laravel App

At first need to open terminal for run the below command to create a new laravel project, if project is already installed then just ignore this step :

composer create-project laravel/laravel LaravelWithVueCrud --prefer-dist
Database Connection

Now in this step i will explains how to make database connection with project by adding database name, username and password in .env config file in our project:

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

Read Also: How to Insert Multiple Records in Laravel?

Set Up Model and Run Migration

Just need to run the below process to respectively create the new Model (database table) and then migration file:

php artisan make:model CompanyName -m

So now add the following code in database/migrations/create_company_names_table.php:

<?php

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

class CreateCompanyNamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('company_names', function (Blueprint $table) {
            $table->id();
            $table->string('company_name');
            $table->text('detail'); 
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('company_names');
    }
}

Need to define CompanyName table values in app/Models/CompanyName.php:

Read Also: How to Select Count Query with Groupby In Laravel?

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CompanyName extends Model
{
    use HasFactory;
    protected $fillable = [
        'company_name', 
        'detail'
    ];
}

Next step , we need to run migration by using below command:

php artisan migrate
Create Product Controller

Now we will create the companynamecontroller and then define the CRUD operations methods:

php artisan make:controller CompanyNameController

So now open the file and update with the below code in your file in this location app\Http\Controllers\CompanyNameController.php:

Read Also: How can we increase throttle lockout time and max Login Attempts in Laravel?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\CompanyName;

class CompanyNameController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $company_names = CompanyName::all()->toArray();
        return array_reverse($company_names); 
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       
        $company = new CompanyName([
            'company_name' => $request->input('company_name'),
            'detail' => $request->input('detail')
        ]);
        $company->save();

        return response()->json('Company created!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $company = CompanyName::find($id);
        return response()->json($company);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $company = CompanyName::find($id);
        $company->update($request->all());

        return response()->json('Company updated!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $company = CompanyName::find($id);
        $company->delete();
        return response()->json('Company deleted!');
    }
}
Create CRUD Routes

Then open routes/web.php file, in here; we need to define the following route:

Read Also: How to Set Config File Value in Laravel?

<?php

use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('admin.home_page');
});

Next step , we need to open the routes/api.php file. At first, import the companyname controller on top, then define for the CRUD API routes in the route group method as given in the below:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('api')->group(function () {
    Route::resource('Company', App\Http\Controllers\CompanyNameController::class);

});

Read Also: Laravel Toastr Notifications Example

Install Laravel Vue UI

Now need to run composer command for install Vue UI in our laravel application. it will run vue laravel scaffold:

composer require laravel/ui
php artisan ui vue

And After that, we will use the bellow command for install the vue router and for the vue axios packages. These packages will be used to consume the Laravel CRUD APIs.

npm install vue-router vue-axios

next need to run the command to install npm packages:

npm install

Then need to run npm run watch command for compiles all the assets.

npm run watch
Initiate Vue in Laravel

For set up the vue application in Laravel, just we need to create a admin folder in the location resources/views directory and then create an file as name homepage.blade.php file within the admin folder.

Place below code in resources/views/admin/homepage.blade.php file:

Read Also: How to Setup Typescript in Laravel Vue Application?

<!DOCTYPE html>
<html lang="en">

<!-- Mirrored from avenger.kaijuthemes.com/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 05 Dec 2017 03:32:56 GMT -->

<head>
    <meta charset="utf-8">
    <title>Avenger Admin Theme</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="description" content="Avenger Admin Theme">
    <meta name="author" content="KaijuThemes">
    <meta name="csrf-token" value="{{ csrf_token() }}" />

    <link href='http://fonts.googleapis.com/css?family=RobotoDraft:300,400,400italic,500,700' rel='stylesheet'
        type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,400italic,600,700' rel='stylesheet'
        type='text/css'>

    <!--[if lt IE 10]>
        <script src="assets/js/media.match.min.js"></script>
        <script src="assets/js/placeholder.min.js"></script>
    <![endif]-->

    <link href="assets/fonts/font-awesome/css/font-awesome.min.css" type="text/css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="assets/css/styles.css" type="text/css" rel="stylesheet"> <!-- Core CSS with all styles -->

    <link href="assets/plugins/jstree/dist/themes/avenger/style.min.css" type="text/css" rel="stylesheet">
    <!-- jsTree -->
    <link href="assets/plugins/codeprettifier/prettify.css" type="text/css" rel="stylesheet"> <!-- Code Prettifier -->
    <link href="assets/plugins/iCheck/skins/minimal/blue.css" type="text/css" rel="stylesheet"> <!-- iCheck -->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries. Placeholdr.js enables the placeholder attribute -->
    <!--[if lt IE 9]>
        <link href="assets/css/ie8.css" type="text/css" rel="stylesheet">
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/respond.js/1.1.0/respond.min.js"></script>
        <script type="text/javascript" src="assets/plugins/charts-flot/excanvas.min.js"></script>
        <script type="text/javascript" src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- The following CSS are included as plugins and can be removed if unused-->

    <link href="assets/plugins/form-daterangepicker/daterangepicker-bs3.css" type="text/css" rel="stylesheet">
    <!-- DateRangePicker -->
    <link href="assets/plugins/fullcalendar/fullcalendar.css" type="text/css" rel="stylesheet"> <!-- FullCalendar -->
    <link href="assets/plugins/charts-chartistjs/chartist.min.css" type="text/css" rel="stylesheet"> <!-- Chartist -->

</head>

<body class="infobar-offcanvas">
    <div id="app"></div>
    <script src="{{ mix('js/app.js') }}" type="text/javascript"></script>


    <script src="assets/js/jquery-1.10.2.min.js"></script> <!-- Load jQuery -->
    <script src="assets/js/jqueryui-1.9.2.min.js"></script> <!-- Load jQueryUI -->

    <script src="assets/js/bootstrap.min.js"></script> <!-- Load Bootstrap -->


    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>


</body>

<!-- Mirrored from avenger.kaijuthemes.com/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 05 Dec 2017 03:37:03 GMT -->

</html>
Crete Vue CRUD Components

Then next, we need to add the router-view directive in the App.vue file; now this template will help us invoke all the vue routes associated with the all components.

So, need to create App.vue file in resources/js folder, and then put the below code in resources/js/App.vue file:

Read Also: How to Get Selected Option Text in Vue JS ?

<template>
  <div id="wrapper">
    <div id="layout-static">
      <div class="static-sidebar-wrapper sidebar-midnightblue">
        <div class="static-sidebar">
          <div class="sidebar">
            <div class="widget stay-on-collapse" id="widget-welcomebox">
              <div class="widget-body welcome-box tabular">
                <div class="tabular-row">
                  <div class="tabular-cell welcome-avatar">
                    <a href="#">
                      <img src="assets/demo/avatar/avatar_02.png" class="avatar" />
                    </a>
                  </div>
                  <div class="tabular-cell welcome-options">
                    <span class="welcome-text">Welcome,</span>
                    <a href="#" class="name">Jonathan Smith</a>
                  </div>
                </div>
              </div>
            </div>
            <div class="widget stay-on-collapse" id="widget-sidebar">
              <div class="navbar-nav">
                <nav class="navbar navbar-expand-lg navbar-light bg-light">
                  <div class="collapse navbar-collapse">
                    <div class="navbar-nav">
                      <ul>
                        <li>
                          <router-link to="/allcompany" class="nav-item nav-link">Products List</router-link>
                        </li>
                        <li>
                          <router-link to="/create" class="nav-item nav-link">Create Product</router-link>
                        </li>
                        <li>
                          <router-link to="/all-medicine" class="nav-item nav-link">Medicine List</router-link>
                        </li>
                        <li>
                          <router-link
                            to="/create-medicine"
                            class="nav-item nav-link"
                          >Medicine create</router-link>
                        </li>
                      </ul>
                    </div>
                  </div>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="static-content-wrapper">
        <div class="static-content">
          <router-view></router-view>
        </div>
        <footer role="contentinfo">
          <div class="clearfix">
            <ul class="list-unstyled list-inline pull-left">
              <li>
                <h6 style="margin: 0;">&copy; 2015 Avenger</h6>
              </li>
            </ul>
            <button class="pull-right btn btn-link btn-xs hidden-print" id="back-to-top">
              <i class="fa fa-arrow-up"></i>
            </button>
          </div>
        </footer>
      </div>
    </div>
  </div>
</template>
 
<script>
export default {};
</script>

So now, we need to create all the following vue js component files inside the location of resources/js/components folder:

  • AllCompany.vue
  • CreateCompany.vue
  • EditCompany.vue

Now add the bellow code in resources/js/components/AllCompany.vue file. Here in this file we are getting all data from the database and deleting the single company object from the database through vue component.

<template>
    <div>
        <h2 class="text-center">Products List</h2>
 
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Detail</th>
                <!-- <th>Actions</th> -->
            </tr>
            </thead>
            <tbody>
            <tr v-for="company in company_name" :key="company.id">
                <td>{{ company.id }}</td>
                <td>{{ company.company_name }}</td>
                <td>{{ company.detail }}</td>
                <td>
                    <div class="btn-group" role="group">
                        <router-link :to="{name: 'edit', params: { id: company.id }}" class="btn btn-success">Edit</router-link>
                        <button class="btn btn-danger" @click="deleteCompany(company.id)">Delete</button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                company_name: []
            }
        },
        created() {
            this.axios
                .get('http://localhost:8000/api/Company/')
                .then(response => {
                    this.company_name = response.data;
                });
        },
        methods: {
            deleteCompany(id) { 
                this.axios
                    .delete(`http://localhost:8000/api/Company/${id}`)
                    .then(response => {
                        let i = this.company_name.map(data => data.id).indexOf(id);
                        this.company_name.splice(i, 1)
                    });
            }
        }
    }
</script>

Read Also:Get Checked Radio Button Value in Vue JS

Then place the bellow code in resources/js/components/CreateCompany.vue file:

<template>
    <div>
        <h3 class="text-center">Create Product</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="addCompany">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" v-model="company.company_name">
                    </div>
                    <div class="form-group">
                        <label>Detail</label>
                        <input type="text" class="form-control" v-model="company.detail">
                    </div>
                    <button type="submit" class="btn btn-primary">Create</button>
                </form>
            </div>
        </div>
    </div>
</template>
 
<script>
import axios from 'axios'
    export default {
        
        data() {
            return {
                company: {}
            }
        },
        methods: {
            addCompany() {
                this.axios
                    .post('http://localhost:8000/api/Company', this.company)
                    .then(response => (
                        this.$router.push({ name: 'home' })
                    ))
                    .catch(err => console.log(err))
                    .finally(() => this.loading = false)
            }
        }
    }
</script>

Now copy the bellow code to resources/js/components/EditCompany.vue template :

<template>
    <div>
        <h3 class="text-center">Edit Company</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="updateCompany">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" v-model="company.company_name">
                    </div>
                    <div class="form-group">
                        <label>Detail</label>
                        <input type="text" class="form-control" v-model="company.detail">
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                company: {}
            }
        },
        created() {
            this.axios
                .get(`http://localhost:8000/api/Company/${this.$route.params.id}`)
                .then((res) => {
                    this.company = res.data;
                });
        },
        methods: {
            updateCompany() {
                this.axios
                    .patch(`http://localhost:8000/api/Company/${this.$route.params.id}`, this.company)
                    .then((res) => {
                        this.$router.push({ name: 'home' });
                    });
            }
        }
    }
</script>

Read Also: Vue JS Get Array Length Or Object Length

Create Vue CRUD Routes

So in this step, we need to create the vue routes. Now create the routes.js file inside resources/js directory, and then add the code in the resources/js/routes.js file:

import AllCompany from './components/AllCompany.vue';
import CreateCompany from './components/CreateCompany.vue';
import EditCompany from './components/EditCompany.vue';


export const routes = [{
        name: 'home',
        path: '/allcompany',
        component: AllCompany
    },
    {
        name: 'create',
        path: '/create',
        component: CreateCompany
    },
    {
        name: 'edit',
        path: '/edit/:id',
        component: EditCompany
    }
];
Define Vue App.js

Now we are in final step so brings we need to the add the following code in the resources/js/app.js file:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

import Vue from 'vue'

import App from './App.vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router';
import axios from 'axios';
import {
    routes
} from './routes';




Vue.use(VueRouter);
Vue.use(VueAxios, axios);

const router = new VueRouter({
    mode: 'history',
    routes: routes
});

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

Read Also: How to Mailchimp api integration in Laravel ?

Start Laravel Vue CRUD App

For start the CRUD application, we just need to run the two following commands respectively in two different terminals :

npm run watch
php artisan serve

Open the URL in the browser:

http://127.0.0.1:8000

Source Code Download From GitHub clickHere

Read Also: How we can create virtual host in ubuntu apache?

Thanks for read. I hope it help you. For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →