Throughout this Laravel VueJs CRUD example article, you may see and understand how to build Create, read, update, and Delete API and how to consume APIs to carry out CRUD operations in Laravel VueJS application.
In computer science, create, read, update, and delete aren’t simply more words. they may be the foundational building block of each application for creating, reading, updating, and deleting the information. The terminology might be special from time to time, as an instance, retrieval instead of read, regulate incredibly of the update, or destroy alternately of delete.
Also Read:-Laravel CRUD | Laravel 8 CRUD Application Tutorial for Beginners
although, in this laravel vue js CRUD article, we will help you confirm how to integrate the laravel vue js CRUD operations in a single page utility with vue js components and laravel app.
Laravel 8 Vue JS CRUD Operation example
here some step for create laravel vue js web crud applications comply with the below steps:
Step 1: Install Laravel
Step 2: Configuration of Database
Step 3: Create a model and run migration
Step 4: Create and configure the controller
Step 5: Add routes
Step 6: Install Laravel Vue UI
Step 7: Install NPM dependencies
Step 8: Build Vue Js CRUD Components
Step 9: Test Laravel Vue JS CRUD operations
let’s start creating Laravel Vue Js SPA CRUD application progressively.
Step 1: Install fresh Laravel
first of all we want to get clean and new Laravel application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it(ignore this step if project is already installed):
composer create-project laravel/laravel laravel-vue-crud --prefer-dist
Step 2: Configuration of Database
second step, we configure database like database name, username, password etc for CRUD application of laravel. let’s open .env file and fill complete details equal as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Set Up Model and Run Migration
Run the below peocess to respectively create the model (database table) and migration file:
upload following code in database/migrations/create_products_table.php file:
database/migrations/create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('products');
}
}
define Product table values in app/Models/Product.php file:
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
use HasFactory;
protected $fillable = ['name', 'detail'];
}
Now you have to run this migration by firing command:
php artisan migrate
Step 4: Create Product Controller
You need to create the product controller and define the CRUD operations methods:
php artisan make:controller ProductController
Open and update the below code in app\Http\Controllers\ProductController.php file:
app\Http\Controllers\ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller {
public function index() {
$products = Product::all()->toArray();
return array_reverse($products);
}
public function store(Request $request) {
$product = new Product(['name' => $request->input('name'), 'detail' => $request->input('detail') ]);
$product->save();
return response()->json('Product created!');
}
public function show($id) {
$product = Product::find($id);
return response()->json($product);
}
public function update($id, Request $request) {
$product = Product::find($id);
$product->update($request->all());
return response()->json('Product updated!');
}
public function destroy($id) {
$product = Product::find($id);
$product->delete();
return response()->json('Product deleted!');
}
}
Step 5: Create CRUD Routes
Open routes/web.php file, in here; you have to define the following route:
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
Route::get('{any}', function () {
return view('app');
})->where('any', '.*');
next, you need to open the routes/api.php file. First, import the product controller on top, then outline the CRUD API routes inside the route group method as given below:
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/
Route::middleware('api')->group(function () {
Route::resource('products', ProductController::class);
});
Step 6: Install Laravel Vue UI
Run composer command to install Vue UI in laravel, it’s going to appear vue laravel scaffold:
composer require laravel/ui
php artisan ui vue
After that, use the command to install the vue router and vue axios packages. these packages are used to consume Laravel CRUD APIs.
npm install vue-router vue-axios
subsequently, execute the command to install npm packages:
npm install
The npm run watch command compiles the assets, no longer simply that with run watch command you don’t agonize about re-run the compiler over and over once more.
npm run watch
Step 7: Initiate Vue in Laravel
To set up a vue application in Laravel, you need to create a layout folder in the resources/views directory and create an app.blade.php file in the layout folder.
put below code in resources/views/layout/app.blade.php file:
app.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">
<meta name="csrf-token" value="{{ csrf_token() }}" />
<title>VueJS CRUD Operations in Laravel</title>
<link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>
Step 8: Create Vue CRUD Components
subsequent, you have to add the router-view directive in App.vue file; this template will assist invoke all the vue routes associated with the components.
So, create App.js file in resources/js folder, positioned the below code in resources/js/App.js file:
App.js
<template>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse">
<div class="navbar-nav" >
<router-link to="/" class="nav-item nav-link" >Products List< /router-link><router-link to= "/create" class="nav-item nav-link" >Create Product< /router-link>
</div>
</div>
</nav>
<router-view> </router-view>
</div>
</template>
<script>export default{}</script>
Now, you need to create the following vue js Component files in the resources/js/components folder:
AllProduct.vue
CreateProduct.vue
EditProduct.vue
add code in resources/js/components/AllProduct.vue file; in here we have become all data from database and deleting single product object from database thru vue component.
AllProduct.vue
<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="product in products": key="product.id">
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.detail}}</td>
<td>
<div class="btn-group" role="group">
<router-link: to="{name: 'edit', params: {id: product.id}}" class="btn btn-success">Edit</router-link>
<button class="btn btn-danger" @click="deleteProduct(product.id)">Delete</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default{
data(){
return{products:[]}
},
created(){
this.axios.get('http://localhost:8000/api/products/').then(response => {
this.products = response.data;
});
},
methods:{
deleteProduct(id){
this.axios.delete('http://localhost:8000/api/products/${id}').then(response =>{
let i=this.products.map(data=>data.id).indexOf(id);
this.products.splice(i, 1)
});
}
}
}
</script>
Place code in resources/js/components/CreateProduct.vue file:
CreateProduct.vue
<template>
<div>
<h3 class="text-center">Create Product</h3>
<div class="row">
<div class="col-md-6">
<form @submit.prevent="addProduct">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="product.name">
</div>
<div class="form-group">
<label>Detail</label>
<input type="text" class="form-control" v-model="product.detail">
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default{
data(){
return{product:{}}
},
methods:{
addProduct(){
this.axios.post('http://localhost:8000/api/products', this.product).then(response =>(this.$router.push({name: 'home'})))
.catch(err=> console.log(err))
.finally(()=> this.loadin=false)
}
}
}
</script>
Head over to resources/js/components/EditProduct.vue template and add the below code:
EditProduct.vue
<template>
<div>
<h3 class="text-center">Edit Product</h3>
<div class="row">
<div class="col-md-6">
<form @submit.prevent="updateProduct">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="product.name">
</div>
<div class="form-group">
<label>Detail</label>
<input type="text" class="form-control" v-model="product.detail">
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default{
data(){
return{product:{}}
},
created(){
this.axios.get(`http://localhost:8000/api/products/${this.$route.params.id}`).then((res)=>
{this.product = res.data;});
},
methods:{
updateProduct(){
this.axios.patch(`http://localhost:8000/api/products/${this.$route.params.id}`, this.product).then((res)=>
{this.$router.push({name: 'home'});});
}
}
}
</script>
Step 9: Create Vue CRUD Routes
in this step, you need to create vue routes, create routes.js inside resources/js directory, add the code inside the resources/js/routes.js file:
routes.js
import AllProduct from './components/AllProduct.vue';
import CreateProduct from './components/CreateProduct.vue';
import EditProduct from './components/EditProduct.vue';
export const routes = [{
name: 'home',
path: '/',
component: AllProduct
},
{
name: 'create',
path: '/create',
component: CreateProduct
},
{
name: 'edit',
path: '/edit/:id',
component: EditProduct
}
];
Step 10: Define Vue App.js
This very last step brings you to the point where you should include the required packages in the app.js file. without in addition ado, please add the following code inside the resources/js/app.js file:
app.js
/**
* 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');
window.Vue = require('vue');
import App from './App.vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router';
import axios from 'axios';
import {
routes
} from './routes';
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
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),
});
Step 11: Start Laravel Vue CRUD App
to begin the CRUD app, you want to run the two following commands respectively in two different terminals concurrently:
npm run watch
php artisan serve
Now you can open bellow URL to your browser:
http://127.0.0.1:8000
Also Read:
- Success Story: सिर्फ 8 लाख से खड़ा किया 23,567 करोड़ का बिजनेस, ऐसे मिली कामयाबी
- Car Rental Project in PHP and Mysql
- How to make custom BottomNavigationBar in flutter with source code
- How to debugg our flutter application
- How to add login with Facebook in Flutter