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

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

Top Vue.js Developers in USA

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.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

10 Best Vue Icon Component For Your Vue.js App

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.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!