Build Crud App with Laravel and Vue.js
In this post, we will give you information about Build Crud App with Laravel and Vue.js. Here we will give you detail about Build Crud App with Laravel and Vue.js And how to use it also give you a demo for it if it is necessary.
In this Laravel Vue.js Crud Example, You will learn how to implement Laravel Vue.js crud (create, read, update, and delete) spa (Single Page Application) with Vue.js , Vue Router , and Laravel Framework .
In today’s, the most popular JS frameworks are Angular JS and Vue JS. Angular JS and Vue JS are very user-friendly JS frameworks and most popular. It provides to manage the whole project or application without refresh page and powerful jquery validation.
Vue comes pre-packaged with Laravel (along with Laravel Mix , an excellent build tool based on webpack ) and allows developers to start building complex single-page applications without worrying about transpilers, code packaging, source maps, or any other ‘dirty’ aspects of modern frontend development.
Laravel Vue JS CRUD Application (SPA) Example:
- Install Laravel Project
- Configure Database Details
- Install NPM Dependencies
- Create Migration, Model, and Controller
- Define Routes In web.php
- Create a Vue App
- Create Component For Vue App
- Define Route For Crud App in Vue Router
- Include Vue.js Dependencies to app.js
- Update webpack.mix.js
- Run Development Server
Server Requirements
PHP 7.4
Laravel 10.x
MySQL
1. Install Laravel Project
First, open Terminal and run the following command to create a fresh laravel project:
composer create-project --prefer-dist laravel/laravel crud-spa
or, if you have installed the Laravel Installer as a global composer dependency:
laravel new crud-spa
2. Configure Database Details:
After that, Installation Go to the project root directory, open .env file, and set the database detail as follow:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
3. Install NPM Dependencies
Run the following command to install frontend dependencies:
npm install
Next, install vue , vue-router and vue-axios . Vue-axios will be used for calling Laravel backend API. Run the following command on the terminal:
npm install vue vue-router vue-axios --save
Also see: Laravel Livewire Crud Tutorial
4. Create Migration, Model, and Controller
Create a Category model, migration, and controller. Run the following command for that:
php artisan make:model Category -mcr
-mcr this argument will create Model, Migration, and Controller in Single Command.
Now, Open migration file of category from database / migration and replace code in up () function:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
Migrate the database using the following command:
php artisan migrate
Now, Open Category.php model from app / Models and update code into Category.php Model:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Category extends Model {
use HasFactory;
protected $fillable = ['title','description'];
}
?>
Next, Open CategoryController.php and add code in index, store, update, and delete methods as a following:
<?php
namespace AppHttpControllers;
use AppModelsCategory;
use IlluminateHttpRequest;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
$categories = Category::all(['id','title','description']);
return response()->json($categories);
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
$category = Category::create($request->post());
return response()->json([
'message'=>'Category Created Successfully!!',
'category'=>$category
]);
}
/**
* Display the specified resource.
*
* @param AppModelsCategory $category
* @return IlluminateHttpResponse
*/
public function show(Category $category)
{
return response()->json($category);
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param AppModelsCategory $category
* @return IlluminateHttpResponse
*/
public function update(Request $request, Category $category)
{
$category->fill($request->post())->save();
return response()->json([
'message'=>'Category Updated Successfully!!',
'category'=>$category
]);
}
/**
* Remove the specified resource from storage.
*
* @param AppModelsCategory $category
* @return IlluminateHttpResponse
*/
public function destroy(Category $category)
{
$category->delete();
return response()->json([
'message'=>'Category Deleted Successfully!!'
]);
}
}
5. Define Routes In web.php
Now define routes in web.php and api.php routes file. Go to routes folder and open web.php and api.php file and update the following routes:
routes / web.php
<?php
Route::get('{any}', function () {
return view('app');
})->where('any', '.*');
routes / api.php
<?php
Route::resource('category',AppHttpControllersCategoryController::class)->only(['index','store','show','update','destroy']);
6. Create a Vue App
In this step, go-to resource / views directory, create the app.blade.php file, and add the following code to app.blade.php as follow:
<!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>Laravel Vue CRUD App - onlinecode</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<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>
7. Create Component For Vue App
In this step, go-to the resource / js folder, create components folder, and create files as following:
- View app
- Welcome.vue
- Category / List.vue
- Category / Add.vue
- Category / Edit.vue
App.vue is the main file of our Vue app. We will define router-view in that file. All the routes will be shown in App.vue file.
Open Welcome.vue file and Update the following code into that file:
<template>
<div >
<div >
<h1>Build Crud App with Laravel and Vue.js - onlinecode </h1>
<a href="https://onlinecode.org?utm_source=blogExampleRepo" target="_blank">Visit For More Blogs</a>
</div>
</div>
</template>
Open App.vue file and Update the following code into that file:
<template>
<main>
<nav >
<div >
<router-link to="/" href="#">Laravel Vue Crud App - onlinecode</router-link>
<div >
<div >
<router-link exact-active- to="/" >Home</router-link>
<router-link exact-active- to="/category" >Category</router-link>
</div>
</div>
</div>
</nav>
<div >
<router-view></router-view>
</div>
</main>
</template>
<script>
export default {}
</script>
Next, Open resource / js / components / category / List.vue and add following code into file:
<template>
<div >
<div >
<router-link :to='{name:"categoryAdd"}' >Create</router-link>
</div>
<div >
<div >
<div >
<h4>Category</h4>
</div>
<div >
<div >
<table >
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody v-if="categories.length > 0">
<tr v-for="(category,key) in categories" :key="key">
<td>{{ category.id }}</td>
<td>{{ category.title }}</td>
<td>{{ category.description }}</td>
<td>
<router-link :to='{name:"categoryEdit",params:{id:category.id}}' >Edit</router-link>
<button type="button" @click="deleteCategory(category.id)" >Delete</button>
</td>
</tr>
</tbody>
<tbody v-else>
<tr>
<td colspan="4" align="center">No Categories Found.</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"categories",
data(){
return {
categories:[]
}
},
mounted(){
this.getCategories()
},
methods:{
async getCategories(){
await this.axios.get('/api/category').then(response=>{
this.categories = response.data
}).catch(error=>{
console.log(error)
this.categories = []
})
},
deleteCategory(id){
if(confirm("Are you sure to delete this category ?")){
this.axios.delete('/api/category/${id}').then(response=>{
this.getCategories()
}).catch(error=>{
console.log(error)
})
}
}
}
}
</script>
Next, open resource / js / components / category / Add.vue and update following code into file:
<template>
<div >
<div >
<div >
<div >
<h4>Add Category Build Crud App with Laravel and Vue.js </h4>
</div>
<div >
<form @submit.prevent="create">
<div >
<div >
<div >
<label>Title</label>
<input type="text" v-model="category.title">
</div>
</div>
<div >
<div >
<label>Description</label>
<input type="text" v-model="category.description">
</div>
</div>
<div >
<button type="submit" >Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"add-category",
data(){
return {
category:{
title:"",
description:""
}
}
},
methods:{
async create(){
await this.axios.post('/api/category',this.category).then(response=>{
this.$router.push({name:"categoryList"})
}).catch(error=>{
console.log(error)
})
}
}
}
</script>
Next, open resource / js / components / category / Edit.vue and update following code into file:
<template>
<div >
<div >
<div >
<div >
<h4>Update Category</h4>
</div>
<div >
<form @submit.prevent="update">
<div >
<div >
<div >
<label>Title</label>
<input type="text" v-model="category.title">
</div>
</div>
<div >
<div >
<label>Description</label>
<input type="text" v-model="category.description">
</div>
</div>
<div >
<button type="submit" >Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"update-category",
data(){
return {
category:{
title:"",
description:"",
_method:"patch"
}
}
},
mounted(){
this.showCategory()
},
methods:{
async showCategory(){
await this.axios.get('/api/category/${this.$route.params.id}').then(response=>{
const { title, description } = response.data
this.category.title = title
this.category.description = description
}).catch(error=>{
console.log(error)
})
},
async update(){
await this.axios.post('/api/category/${this.$route.params.id}',this.category).then(response=>{
this.$router.push({name:"categoryList"})
}).catch(error=>{
console.log(error)
})
}
}
}
</script>
8. Define Route For Crud App in Vue Router
Now, You need to define Vue routes, so go to resource / js folder, create routes.js file and update the followings code into the file:
const Welcome = () => import('./components/Welcome.vue' /* webpackChunkName: "resource/js/components/welcome" */)
const CategoryList = () => import('./components/category/List.vue' /* webpackChunkName: "resource/js/components/category/list" */)
const CategoryCreate = () => import('./components/category/Add.vue' /* webpackChunkName: "resource/js/components/category/add" */)
const CategoryEdit = () => import('./components/category/Edit.vue' /* webpackChunkName: "resource/js/components/category/edit" */)
export const routes = [
{
name: 'home',
path: '/',
component: Welcome
},
{
name: 'categoryList',
path: '/category',
component: CategoryList
},
{
name: 'categoryEdit',
path: '/category/:id/edit',
component: CategoryEdit
},
{
name: 'categoryAdd',
path: '/category/add',
component: CategoryCreate
}
]
Here we used lazy loading components. Vue JS handles loading components lazily with routes, so on the DOM, you can load components only when they are needed through routes.
9. Include Vue.js Dependencies to app.js
Now, you need to add all routes, vue-axios, and other dependencies.
resource / js / app.js
require('./bootstrap');
import vue from 'vue'
window.Vue = vue;
import App from './components/App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
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),
});
10. Update webpack.mix.js
webpack.mix.js
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
| Build Crud App with Laravel and Vue.js
*/
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
]).vue();
11. Run Development Server for Build Crud App with Laravel and Vue.js
Open terminal and run this command:
npm run watch
php artisan serve
Open localhost: 8000 in the browser.
It’d be a good idea to follow along with the simple demo app that can be found in this GitHub repo .
Hope this code and post will helped you for implement Build Crud App with Laravel and Vue.js. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs