Laravel 5.5 - VueJS 2.0 CRUD Operations

Today, we are share with you VueJS 2.0 CRUD (insert, update, delete and listing) oparation in laravel 5.5, we all are known laravel 5.5 and VueJS 2.0 is best combination for development any web application. in this article we are show you how to make laravel 5.5 and VueJS 2.0 crud in step by step don't warry if you are beginner, intermediate or expert in laravel or VueJS. simply follow this all step any easyly make VueJS 2.0 CRUD with laravel 5.5

Before starting vuejs crud with laravel you required following things in your system.

Development Server Requirements:

PHP >= 7.0.0

OpenSSL PHP Extension

PDO PHP Extension

Mbstring PHP Extension

Tokenizer PHP Extension

XML PHP Extension

Apache/Nginx

MySQl

Composer

NodeJs with NPM

Step : 1 Create Laravel Project:

First, we need to create one laravel fresh project using composer. simply run following command in your terminal for create new laravel project.


composer create-project --prefer-dist laravel/laravel ProjectName
	
Step : 2 Configure .env

Next, after create laravel project open .env file and configure your database setting like that.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=YOUR-DATABASE-NAME
DB_USERNAME=DATABASE-USERNAME
DB_PASSWORD=DATABASE-USER-PASSWORD
	
Step : 3 Create Post Table Migration:

Next, we are create one post table migration for make all crud oparation on it. simple run following command and create migration file.


php artisan make:migration create_post_table --create=posts
	

After create migration open migration file and make change in it like that.


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

class CreatePostTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
	

Then run migration using following command.


php artisan migrate
	
Step : 4 Create Post Table Model And Controller:

Next, we are create Post table model and controller run by following command.


php artisan make:model Post -r
	

You can locate the model at /app/Post.php and controller at /app/Http/Controllers/PostController.php

Next, open your model app/Post.php file and make following change.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'title',
        'description',
    ];
}
	

app/Http/Controllers/PostController.php


namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::get();
        return response()->json([
            'posts'    => $posts,
        ], 200);
    }

    /**
     * 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)
    {
        $this->validate($request, [
            'title'        => 'required|max:255',
            'description' => 'required',
        ]);
 
        $post = Post::create([
            'title'        => request('title'),
            'description' => request('description'),
        ]);
 
        return response()->json([
            'post'    => $post,
            'message' => 'Success'
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $this->validate($request, [
            'title'        => 'required|max:255',
            'description' => 'required',
        ]);
 
        $post->title = request('title');
        $post->description = request('description');
        $post->save();
 
        return response()->json([
            'message' => 'Post updated successfully!'
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        //
    }
}
	
Step : 5 Create Post Route:

Next, we need to create insert, update, index, delete, create routes for this crud. we are make crud so resource route is best. i hope you all are very well known resource Route.


Route::resource('/posts', 'PostController');	
	
Step : 6 Register Vue Component:

Next, we are need to register vuejs component in /resources/assets/js/app.js file open it and make following changes


/**
 * 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');

/**
 * 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.component('example', require('./components/Example.vue'));

Vue.component('posts', require('./components/Post.vue'));

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

After add component open your /resources/views/home.blade.php file and make following changes


@extends('layouts.app')

@section('content')
<posts></posts>
@endsection
	
Step : 7 Create New VueJS Component:

Next, we are use here vue js 2.0 for front. and we all are known laravel provide bydefault setting for vue js for easy to develope front layout.

Here, we are create one vue js component file Post.vue in /resources/assets/js/components/ folder


<template>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">My Post</div>

                    <div class="panel-body">

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <button @click="initAddPost()" class="btn btn-primary btn-xs pull-right">
                            + Add New Post
                        </button>
                        My Post
                    </div>

                    <div class="panel-body">
                        <table class="table table-bordered table-striped table-responsive" v-if="posts.length > 0">
                            <tbody>
                                <tr>
                                    <th>
                                        No.
                                    </th>
                                    <th>
                                        Title
                                    </th>
                                    <th>
                                        Description
                                    </th>
                                    <th>
                                        Action
                                    </th>
                                </tr>
                                <tr v-for="(posts, index) in posts">
                                    <td>{{ index + 1 }}</td>
                                    <td>
                                        {{ posts.title }}
                                    </td>
                                    <td>
                                        {{ posts.description }}
                                    </td>
                                    <td>
                                        <button @click="initUpdate(index)" class="btn btn-success btn-xs">Edit</button>
                                        <button @click="deletePost(index)" class="btn btn-danger btn-xs">Delete</button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" tabindex="-1" role="dialog" id="add_post_model">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">×</span></button>
                        <h4 class="modal-title">Add New Post</h4>
                    </div>
                    <div class="modal-body">

                        <div class="alert alert-danger" v-if="errors.length > 0">
                            <ul>
                                <li v-for="error in errors">{{ error }}</li>
                            </ul>
                        </div>

                        <div class="form-group">
                            <label for="title">Title:</label>
                            <input type="text" name="title" id="title" placeholder="Title Name" class="form-control"
                                   v-model="posts.title">
                        </div>
                        <div class="form-group">
                            <label for="description">Description:</label>
                            <textarea name="description" id="description" cols="30" rows="5" class="form-control"
                                      placeholder="Post Description" v-model="posts.description"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" @click="createPost" class="btn btn-primary">Submit</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

        <div class="modal fade" tabindex="-1" role="dialog" id="update_post_model">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                        <h4 class="modal-title">Update Post</h4>
                    </div>
                    <div class="modal-body">
 
                        <div class="alert alert-danger" v-if="errors.length > 0">
                            <ul>
                                <li v-for="error in errors">{{ error }}</li>
                            </ul>
                        </div>
 
                        <div class="form-group">
                            <label>Title:</label>
                            <input type="text" placeholder="Title" class="form-control"
                                   v-model="update_post.title">
                        </div>
                        <div class="form-group">
                            <label for="description">Description:</label>
                            <textarea cols="30" rows="5" class="form-control"
                                      placeholder="Task Description" v-model="update_post.description"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" @click="updatePost" class="btn btn-primary">Submit</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

    </div>
</template>

<script>
    export default {
        data(){
            return {
                posts: {
                    title: '',
                    description: ''
                },
                errors: [],
                posts: [],
                update_post: {}
            }
        },
        mounted()
        {
            this.readPosts();
        },
        methods: {
            initAddPost()
            {
                this.errors = [];
                $("#add_post_model").modal("show");
            },
            createPost()
            {
                axios.post('/posts', {
                    title: this.posts.title,
                    description: this.posts.description,
                })
                    .then(response => {

                        this.reset();

                        $("#add_post_model").modal("hide");

                    })
                    .catch(error => {
                        this.errors = [];
                        if (error.response.data.errors.title) {
                            this.errors.push(error.response.data.errors.title[0]);
                        }

                        if (error.response.data.errors.description) {
                            this.errors.push(error.response.data.errors.description[0]);
                        }
                    });
            },
            reset()
            {
                this.posts.title = '';
                this.posts.description = '';
            },
            readPosts()
            {
                axios.get('/posts')
                    .then(response => {

                        this.posts = response.data.posts;

                    });
            },
            initUpdate(index)
            {
                this.errors = [];
                $("#update_post_model").modal("show");
                this.update_post = this.posts[index];
            },
            updatePost()
            {
                axios.patch('/posts/' + this.update_post.id, {
                    title: this.update_post.title,
                    description: this.update_post.description,
                })
                    .then(response => {
 
                        $("#update_post_model").modal("hide");
 
                    })
                    .catch(error => {
                        this.errors = [];
                        if (error.response.data.errors.title) {
                            this.errors.push(error.response.data.errors.title[0]);
                        }
 
                        if (error.response.data.errors.description) {
                            this.errors.push(error.response.data.errors.description[0]);
                        }
                    });
            },
            deletePost(index)
            {
                let conf = confirm("Do you ready want to delete this post?");
                if (conf === true) {

                    axios.delete('/posts/' + this.posts[index].id)
                        .then(response => {

                            this.posts.splice(index, 1);

                        })
                        .catch(error => {

                        });
                }
            }
        }
    }
</script>
	
Step : 8 How To Run:

Our crud oparation run now how to run it. please simple follow this step.

run following command for install npm dependancy


npm install
	

Now run following command for deploy nmp setup and Compile Assets and Use Post Controller:


npm run dev
	

Now we are ready to run our example so run bellow command ro quick run:


php artisan serve

Now you can open bellow URL on your browser:

	
http://localhost:8000/

Now, register new user and you see your VueJS crud

If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...

 Prev post

Next post