X
    Categories: FeaturedLearn Laravel Tutorials, Tips And Guides
Reading Time: 9 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.

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 host my Laravel on Cloudways managed servers 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.

You might also like: How To Install Laravel On DigitalOcean

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

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->
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.

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

 

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