Create a Laravel Vue Single Page App

Create a Laravel Vue Single Page App

Laravel has become the most popular choice for developing PHP projects. One important reason for this popularity is the built in support for Vue.js, a very fast growing JavaScript library for developing impressive front-ends.

This combination results is fast, secure and very impressive applications that need minimum time to go from ideation to final code review. The support for Vue.js means that Laravel developers could use Vue components easily within their apps without wasting time in writing integrations for the components. To demonstrate the support, I decided to create a single page app in Laravel with a Vue.js powered frontend.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • WAMP/XAMPP environment
  • Laravel 5.5
  • PHP 7.1
  • MySQL
  • Node.js with NPM

To make sure that that I don’t get distracted by server level issues, I decided to deploy Laravel to a server using Cloudways managed platform because it takes care of server level issues and has a great devstack right out of the box. You can try out Cloudways for free by signing for an account and then following this simple GIF for setting up the server and the Laravel application.

Install Node.js with NPM

The first step is the installation of Node.js with NPM.

For this first install Node.js. Next go to the project’s folder and type the following command in the terminal:

npm init
npm install

This command will install all the JavaScript dependencies for VueJS. In addition, the command will also install laravel-mix, an API for defining webpack.

Configure the Database

Now setup the MySQL database and configure it in Laravel.

In the project root, you will find the .env and config/database.php files. Add the database credentials (username, DB name, and password) to setup the database and allow the Laravel Single page app to access it.

Create the Migrations

In the third step, open the terminal and go to the root of the newly created Laravel project and generate a new migration to create task table:

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

Next , open the migration file located in the database/migration folder and replace the up()function with the following code:

public function up()

   {

       Schema::create('tasks', function (Blueprint $table) {

           $table->increments('id');

           $table->string('name');

           $table->unsignedInteger('user_id');

           $table->text('description');

           $table->timestamps();

       });

   }

Next , In the app/Providers/AppServiceProvider.php file, the boot method sets a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()



{

Schema::defaultStringLength(191);

}

Run the Migration

Create the tables in the database by using the following command:

Php artisan migrate

Setup User Authentication

Laravel provide default user authentication in which you can register users who can then login through the provided login system. This login system also provides Laravel CRSF authentication token to further strengthen the security of the application against malicious exploits. Use the following command to set up user authentication in the Laravel Vue SPA:

php artisan make:auth

Create Task Model and Task Controller

Create task model because I will handle database operations through Laravel Eloquent. I also need a controller to handle user requests such as create, read, update and delete operations.

Use the following command to create the model and the controller:

php artisan make:model Task -r

Next open the Task Model which in app/Task.php and controller at /app/Http/Controllers/TaskController.php. Update the model code with the following code.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Validation\Validator;
class Task extends Model
{
   protected $fillable = [
       'name',
       'user_id',
       'description',
   ];
}

The Code for Controller

Next, update the controller file with the following code.

<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class TaskController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index()
   {
       $tasks = Task::where(['user_id' => Auth::user()->id])->get();
       return response()->json([
           'tasks'    => $tasks,
       ], 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)
   {
        }
   /**
    * 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)
   {
   }
}

Middleware

To setup middleware, add the following code to the Task Controller.

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

Create the Method

In the store() method of Task Controller, update the following code to add data into database.

$this->validate($request, [
           'name'        => 'required',
           'description' => 'required',
       ]);
       $task = Task::create([
           'name'        => request('name'),
           'description' => request('description'),
           'user_id'     => Auth::user()->id
       ]);
       return response()->json([
           'task'    => $task,
           'message' => 'Success'
       ], 200);

Update Method

In Update() method of Task Controller, update the following code to edit database data. database.

$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);

Delete Method

In the Destroy() method of Task Controller,  the following code will delete data from the database.

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

Route Set up in Laravel SPA

Route sets the application URL and the controller method for the URL. Routes are located in route/web.php and contains the following code:

Route::get('/home', '[email protected]')->name('home');
Route::resource('/task', 'TaskController');

Create Vue.js Components

Create a new file for Task component inside /resources/assets/js/components/ folder namedTask.vue and add following sample 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 Assigments</div>
                   <div class="panel-body">
                   </div>
               </div>
           </div>
       </div>
   </div>
</template>
<script>
   export default {
       mounted() {
       }
   }
</script>

The component is ready for registration. Open app.js file from /resources/assets/js/app.jsand add the following line after example component registration line:

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

Compile Assets

Use the following command to compile the newly added code as a Vue.js component. This will also register component:

npm run dev

Calling in the View

Now open home.blade.php located in /resources/views/ and update it as follows:

@extends('layouts.app')
@section('content')
<task></task>
@endsection

Create Update & Delete in Task.vue

The Task component is located inside /resources/assets/js/components/ and is named Task.vue. Open this file and update the code:

<template>
   <div class="container">
       <div class="row">
           <div class="col-md-12">
               <div class="panel panel-default">
                   <div class="panel-heading">
                <h3><span class="glyphicon glyphicon-dashboard"></span> Assignment Dashboard </h3> <br>
                    <button @click="initAddTask()" class="btn btn-success " style="padding:5px">
                     Add New Assignment
                     </button>
                   </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-for="(task, index) in tasks">
                               <td>{{ index + 1 }}</td>
                               <td>
                                   {{ task.name }}
                               </td>
                               <td>
                                   {{ task.description }}
                               </td>
                               <td>
 <button @click="initUpdate(index)" class="btn btn-success btn-xs" style="padding:8px"><span class="glyphicon glyphicon-edit"></span></button>

 <button @click="deleteTask(index)" class="btn btn-danger btn-xs" style="padding:8px"><span class="glyphicon glyphicon-trash"></span></button>
                               </td>
                           </tr>
                           </tbody>
                       </table>
                   </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-for="error in errors">{{ error }}</li>
                           </ul>
                       </div>
                       <div class="form-group">
                           <label for="names">Name:</label>
                           <input type="text" name="name" id="name" placeholder="Task Name" class="form-control"
                                  v-model="task.name">
                       </div>
                       <div class="form-group">
                           <label for="description">Description:</label>
                           <textarea name="description" id="description" cols="30" rows="5" class="form-control"
                                     placeholder="Task Description" v-model="task.description"></textarea>
                       </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                       <button type="button" @click="createTask" 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_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">Update Task</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>Name:</label>
                           <input type="text" placeholder="Task Name" class="form-control"
                                  v-model="update_task.name">
                       </div>
                       <div class="form-group">
                           <label for="description">Description:</label>
                           <textarea cols="30" rows="5" class="form-control"
                                     placeholder="Task Description" v-model="update_task.description"></textarea>
                       </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                       <button type="button" @click="updateTask" class="btn btn-primary">Submit</button>
                   </div>
               </div><!-- /.modal-content -->
           </div><!-- /.modal-dialog -->
       </div><!-- /.modal -->
   </div>
</template>
<script>
   export default {
       data(){
           return {
               task: {
                   name: '',
                   description: ''
               },
               errors: [],
               tasks: [],
               update_task: {}
           }
       },
       mounted()
       {
           this.readTasks();
       },
       methods: {
           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 => {
                       });
               }
           },
           initAddTask()
           {
               $("#add_task_model").modal("show");
           },
           createTask()
           {
               axios.post('/task', {
                   name: this.task.name,
                   description: this.task.description,
               })
                   .then(response => {
                       this.reset();
                       this.tasks.push(response.data.task);
                       $("#add_task_model").modal("hide");
                   })
                   .catch(error => {
                       this.errors = [];
                       if (error.response.data.errors && error.response.data.errors.name) {
                           this.errors.push(error.response.data.errors.name[0]);
                       }
if (error.response.data.errors && error.response.data.errors.description)
                      {
                           this.errors.push(error.response.data.errors.description[0]);
                       }
                   });
           },
           reset()
           {
               this.task.name = '';
               this.task.description = '';
           },
           readTasks()
           {
               axios.get('http://127.0.0.1:8000/task')
                   .then(response => {
                       this.tasks = response.data.tasks;
                   });
           },
           initUpdate(index)
           {
               this.errors = [];
               $("#update_task_model").modal("show");
               this.update_task = this.tasks[index];
           },
           updateTask()
           {
               axios.patch('/task/' + this.update_task.id, {
                   name: this.update_task.name,
                   description: this.update_task.description,
               })
                   .then(response => {
                       $("#update_task_model").modal("hide");
                   })
                   .catch(error => {
                       this.errors = [];
                       if (error.response.data.errors.name) {
                           this.errors.push(error.response.data.errors.name[0]);
                       }
                       if (error.response.data.errors.description) {
                           this.errors.push(error.response.data.errors.description[0]);
                       }
                   });
           }
       }
   }
</script>

Now run the following command to compile the newly added code as a Vue.js component:

npm run dev

Conclusion

This Laravel single page app is a simple demonstration of how to combine Laravel and Vue.js into an effective frontend and backend. I am sure you could easily extend this idea into a powerful application that simplify development. Here is the application in action. Do give it a try and let me know how it went in the comments below.

Do leave a comment if you need help in understanding the code or the idea.

Further reading:

Accessing properties globally in Vue.js with prototypes

Dockerizing a Vue Application

Building simple chat web app using Vue.js and Firebase

Build Firestore Database CRUD Web App using Vue.js and Firebase

How to deploy your Vue app with Netlify

MEVN Stack Tutorial With Example From Scratch

Using Renderless Components in Vue.js

An API Gateway Example Bringing Together Vue.js, Express, and Postgres

Building Micro Frontends with React, Vue, and Single-spa

How to implement client-side pagination in Vue.js

vue-js laravel

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Laravel 7 VUE JS Example | Laravel 7 VUE JS Tutorial For Beginners

Laravel 7 VUE JS Exmples. Here you will learn laravel vue js from scratch. This tutorial provides following laravel vue js tutorial from scratch. <div class="gen-info-box"><b>Recommended:-</b> <a...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

Inertia.js for Laravel & Vue - Server Driven Single Page Apps

We take a look at the basics of Inertia.js and build out a simple CRUD application in Laravel and Vue. What is Inertia.js? Inertia is a library that combines the best of both server-side rendering (SSR) and client-side rendering (CSR) by allowing developers to build SPAs using server-side routing and controllers.

PJ Blog is an open source blog built with Laravel and Vue.js

PJ Blog is an open source blog built with Laravel and Vue.js.

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.