Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Create a Laravel Vue Single Page App in Under an Hour

February 23, 2018

8 Min Read
laravel spa
Reading Time: 8 minutes

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.

The combination Laravel Vue JS results in 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.

Why You Should Use Vue with Laravel

VueJS is simple and less opinionated than other frameworks. It has a CLI project generator which makes it easy to build a project prototype having a temporary structure. Its CLI execute an upgradeable runtime dependency which can be extended using a plugin.

Vue offers variety of default options for different tasks, and also provides pre-established conventional environment for building enterprise level applications. The framework’s syntax is completely harnessed from the JavaScript expression.

Nowadays, there is a big fuss over why should we should use VueJS with Laravel. The question here is to ask what does Vue has to offer and how it will comply with our functional needs.

Here are some of the important features that makes VueJS a pretty handy tool to use with Laravel:

Front-end is Everything

Today, the whole internet is event-driven, and these events are being updated on the screen displayed to the user. So, for the user to be up-to-date, there is no need to refresh their page again and again, thanks to JavaScript.

Reactiveness of Vue

A highly interactive frontend can be built using VueJS, in which the display of the user is event-driven and all the activity around him is updated quickly. The framework provides an amazing experience for the users, as it can trigger UI changes dynamically and can couple them very nicely with Laravel.

Single Page WebApp

In remote countries where accessing the internet sometimes becomes difficult, a single page application gives ease to load the URL if it is cached earlier. It allows users to access the application multiple times, as it is saved earlier in the caches requiring less time to load in the browser.

Easy to Use

Vue is really easy to get started with as it works with simple concept of JavaScript. It allows you to build non-trivial applications within minutes, as it is pretty straightforward and easy to understand. Moreover, if your template is built on HTML, it automatically becomes valid for VueJS as it requires no additional scripting to change the existing structure. 

Prerequisites

For the purpose of this Laravel Vue JS tutorial, I assume that you have a Laravel application installed on a web server.

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 stack right out of the box. You can try out Cloudways for free by signing for an account.

Lightning Fast Laravel Hosting With 24×7 Tech Support

We Take Care of Your Hosting Hassles To Let You Focus More On The Business

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.

You might also like: Set up Easy Vue Pagination for Laravel

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 for Laravel SPA, 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);

You Might Also Like: Vue Validation in Laravel to Handle Form Requests

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', 'HomeController@index')->name('home');

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

Advanced Laravel Hosting For 5x REST API Performance

Speed Up Your App Performance With Our Powerful Laravel Hosting Now

Create Vue.js Components

Create a new file for Task component inside /resources/assets/js/components/ folder named Task.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.js and add the following line after example component registration line:

app.js:

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

You might also like: Create A Realtime Chatroom With Laravel, VueJS And Pusher

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 Vue JS into an effective frontend and backend. I am sure you could easily extend this idea into a powerful application that simplify development. Do give this Vue JS and Laravel SPA tutorial and let me know how it went in the comments below.

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

Please Retweet if you liked this Laravel Vue JS article, and don’t hesitate to follow me on Twitter. Thanks for reading.

 

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Pardeep Kumar

Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. You can email him at pardeep.kumar@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019