Laravel 5.5 VueJs 2.0 CRUD Operations Application

Laravel 5.5 and VueJS 2.0 is the best combination for the development of any kind of projects in the web development world, no matters if your PHP beginner, intermediate or expert developer as long as your PHP Laravel developer you should be using this combination into your project to make it more flexible and advanced with the help of VueJs 2.0.

VueJs 2.0 is progressive framework for building user interfaces and you know Laravel 5.5 comes with the predefined configuration for VueJS 2.0 to start building the application, you don’t have to worry about configuration part.

I am guessing you have your PHP environment setup and ready to run Laravel 5.5 application if not please make sure you have your development environment ready along with the following server requirements installed or I would suggest to use homestead for your local development.

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 new Laravel Project:

Create new Laravel project by using following commands with your terminal/command line:

Using Laravel installer:

$ laravel new project-name

OR create using Composer

$ composer create-project --prefer-dist laravel/laravel project-name

Step 2: Database Design and Configuration:

Create new database migration file using php artisan:

Open your terminal/command-line application and cd into the root of newly created Laravel project and generate new migration to create task table:

$ cd /path-to-project/project-name
$ php artisan make:migration create_tasks_table --create=tasks

Open migration file for task table, it should be located inside /database/migrations directory and update up() function according to the following script:

    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->unsignedInteger('user_id');
            $table->text('description');
            $table->timestamps();
        });
    }

Configure Laravel database settings:

We will required a MySQL database at the backend to access and store the crud application data, so you need to create fresh database first. so go ahead and create new database in MySQL and come up with the database name, database username and password.

Open .env file from the root of the application and Update following database settings:

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

Make sure to match above settings with your MySQL database credentials.

Run Laravel Migration:

Use following command to run Laravel migration to create our tasks table by using migration file.

$ php artisan migrate

The above command should generate output like this:

Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2017_10_06_080114_create_tasks_table
Migrated:  2017_10_06_080114_create_tasks_table

Laravel will create two extra table for as you know we have build migrations files for users and password resets table.

Step 3: User Authentication:

Let’s use Laravel default user authentication quick-start, it is going to provide us an ability to register a new user, login ability for the user, routes, controllers and predefined views out of the box.

Use following command to generate User Authentication.

$ php artisan make:auth
Authentication scaffolding generated successfully.

If you see above message that means you have generate authentication successfully, now you can check login register pages by navigating your browser to /login and /register.

Login Screen:

Login Screen

Registration Screen:

Registration screen

We have our user authentication part ready to use go ahead and register new user, so that you would be able to see home view of the application, as I did you can see the screen below:

User Home – Dashboard Page

Step 4: Create Task Model and Task Controller

We are going to required a Task Model to handle database operation throughout Laravel Eloquent and a controller to handle user request such as create, read, update and delete the task.

Use following Command from your terminal to generate Model and Resource Controller for Task:

$ php artisan make:model Task -r

The above command should output following messages:

Model created successfully.
Controller created successfully.

You can locate the model at /app/Task.php and controller at /app/Http/Controllers/TaskController.php

Task Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    //
}

Task Controller:

<?php

namespace App\Http\Controllers;

use App\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */    public function index()
    {
        //
    }

    /**
     * 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)
    {
        //
    }

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Task  $task
     * @return \Illuminate\Http\Response
     */    public function update(Request $request, Task $task)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Task  $task
     * @return \Illuminate\Http\Response
     */    public function destroy(Task $task)
    {
        //
    }
}

We need to update Task model here to have fillable attributes so that we should be able to insert the new task:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = [
        'name',
        'user_id',
        'description',
    ];
}

And Update the TaskController to have user middleware attached so that it is only going to be accessible to for the authenticated users, go ahead and add following constructer function into the TaskController.php file:

    public function __construct()
    {
        $this->middleware('auth');
    }

Step 5: Create Required Routes:

As you know we need to deal with the CRUD operations here so it’s better to have resource route added into our routes file that is web.php file.

Go ahed and add following line at the last of your web.php file which is location at /routes/web.php

Route::resource('/task', 'TaskController');

The above single line will provide us bunch of routes to handle crud operations with Task, you can also have a look on those routes by using $ php artisan route:list command.

Step 6: Create New VueJS Component:

It’s time to dive into the VueJs 2.0 as you know we are going to use VueJs for our front end user interface development.

Create new file for Task component inside /resources/assets/js/components/ folder named Task.vue and add following sample line of code:

Task.vue:

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

                    <div class="panel-body">

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

<script>
    export default {
        mounted() {

        }
    }
</script>

Keep in mind we will need to update this component later on for now I want to your to test how you should add and register new component in vuejs 2.0.

So our component ready to register, open app.js file from /resources/assets/js/app.js add following line after example component registration line:

app.js:

Vue.component('task', require('./components/Task.vue'));

The complete app.js file should look like this:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));
Vue.component('task', require('./components/Task.vue'));

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

Step 7: Install npm Package Dependencies:

You know Laravel comes with the Laravel mix to compile SASS, JS etc. to use Laravel mix we have install required dev dependencies to run package scripts.

Use following command to install required dependencies:

$ npm install

It will take some time, depending on your internet connection speed.

added 1334 packages in 132.059s

When you so message like this at the of the your terminal that means our dependencies are installed we are good to go.

Step 8: Compile Assets and Use Task Controller:

Run npm run dev command as showing below to compile our newly added code such as a VueJs Component and Component registration:

$ npm run dev

If you success like “DONE Compiled successfully in 9582ms” this then we are ready to move.

Now open home.blade.php file from /resources/views/home.blade.php and update it accordingly:

@extends('layouts.app')

@section('content')
<task></task>
@endsection

And visit browser to login into the application to see if we got some change, see screen below:

Task Component Test

As you see in the above screen we have got our Task component running successfully.

Step 9: Implement Create Task Operation:

It’s time to move on to our real goal to accomplish create, read, update and delete operations in this step let’s see how we should deal with the Create Task Operation.

We will do two things here first is validate the request on server and create task valid requests.

Open Task.vue Component and update according to the following script:

/resources/assets/js/components/Task.vue:

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

                    <div class="panel-body">

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

        <div class="modal fade" tabindex="-1" role="dialog" id="add_task_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">&times;</span></button>
                        <h4 class="modal-title">Add New Task</h4>
                    </div>
                    <div class="modal-body">

                        <div class="alert alert-danger" v-if="errors.length > 0">
                            <ul>
                                <li v->
If you see in the above script we are using Bootstrap model popup as well and in the script section we are dealing with the VueJs data and methods and by using axios I am handling the ajax request.

Next update the TaskController to handle create operations, update store method as showing below:

/app/Http/Controllers/TaskController.php:
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'        => 'required|max:255',
            'description' => 'required',
        ]);

        $task = Task::create([
            'name'        => request('name'),
            'description' => request('description'),
            'user_id'     => Auth::user()->id
        ]);

        return response()->json([
            'task'    => $task,
            'message' => 'Success'
        ], 200);
    }

Run following command from terminal and to test application:

$ npm run dev

Login to the application from browser you should see following screen with Add new Task button added:

Task component - Add New Task Button

Click Add New Task button, you should see model popup showing below and try to click submit button to see validation errors:

Task Validation Errors

Step 10: Implement Read Records Operations:

Our second feature of the application is Reading the records, let's implement that, go ahead and open your Task.vue component and replace with the following script:

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

                    <div class="panel-body">
                        <table class="table table-bordered table-striped table-responsive" v-if="tasks.length > 0">
                            <tbody>
                                <tr>
                                    <th>
                                        No.
                                    </th>
                                    <th>
                                        Name
                                    </th>
                                    <th>
                                        Description
                                    </th>
                                    <th>
                                        Action
                                    </th>
                                </tr>
                                <tr v->
And open TaskController to update index() function:
    public function index()
    {
        $tasks = Task::where(['user_id' => Auth::user()->id])->get();
        return response()->json([
            'tasks'    => $tasks,
        ], 200);
    }

You can run the npm run dev command again from command line to compile assets and open your browser again and refresh the screen to see the you recently crated task listed, you can also checkout in the screen below:

Read All Tasks

Step 11: Implement Update Task Action:

Same thing we have to deal with the edit button action as well update patch request, I have ready in the below script:

Again open you Task component and replace with the following script:

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

                    <div class="panel-body">
                        <table class="table table-bordered table-striped table-responsive" v-if="tasks.length > 0">
                            <tbody>
                            <tr>
                                <th>
                                    No.
                                </th>
                                <th>
                                    Name
                                </th>
                                <th>
                                    Description
                                </th>
                                <th>
                                    Action
                                </th>
                            </tr>
                            <tr v->
And open Task controller to change the update() method as follows:
public function update(Request $request, Task $task)
    {
        $this->validate($request, [
            'name'        => 'required|max:255',
            'description' => 'required',
        ]);

        $task->name = request('name');
        $task->description = request('description');
        $task->save();

        return response()->json([
            'message' => 'Task updated successfully!'
        ], 200);
    }

Save the file open you terminal and execute npm run dev command again and visit to your browser to test update task action as showing below:

Click Edit button from the list to see Update Task Model popup:

Update Task Model Popup

Hit Submit button to update the task:

Updated Task Records List

Step 12: Handle Delete Operation:

Final step of the tutorial, to handle delete record/task action, let's do that:

Open Task.vue component and update following section:

Change delete button script to:

<button @click="deleteTask(index)" class="btn btn-danger btn-xs">Delete</button>

And add following new method under methods section:

            deleteTask(index)
            {
                let conf = confirm("Do you ready want to delete this task?");
                if (conf === true) {

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

                            this.tasks.splice(index, 1);

                        })
                        .catch(error => {

                        });
                }
            }

Open TaskController and update destroy method:

/app/Http/Controllers/TaskController.php:

    public function destroy(Task $task)
    {
        $task->delete();
        return response()->json([
            'message' => 'Task deleted successfully!'
        ], 200);
    }

Finally execute npm run dev or npm run prod command to compile the code and test your application.

Conclusion:

What your learn from this tutorial?

Many things, such as

  • Installing Laravel new application
  • Generating new migration
  • Execute migration
  • Updating Database Settings
  • Creating Eloquent Model and updating fillable properties
  • Creating Laravel Resource Controller
  • Adding Resource Routes
  • Using Laravel User Authentication
  • Create and register new VueJs 2.0 Component
  • Installing required dependencies and Asset compilation
  • How to use VueJs 2.0 Component
  • Handling Ajax request with help of axios and vuejs
  • Laravel Eloquent operations Read, Create, Update and Delete
  • Handling CRUD user interface with VueJs 2.0 along with Laravel
  • Using Bootstrap Model popup in VueJS 2.0 with example
  • Using Bootstrap Table and Panel.

Next Read Recommendation - Laravel 5 VueJS Routing Building Single Page Application

Thanks for being a part of iTech Empires, let me know if you get any issue running above CRUD application by using comment section below:

Take care, I will see you in next tutorial.

Yogesh Koli

Software engineer & Blogger lives in India, has 6+ years of experience working with the front-end and back-end web app development.

View Comments

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example of using Eloquent Subqueries and…

4 months ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify arrays in php here I…

4 months ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter array in php here I…

4 months ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the best and essential feature that…

4 months ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them, what are the advantage of…

4 months ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super useful to optimize your laravel…

4 months ago