Laravel Vuejs Handbook
Laravel Vuejs Handbook
avelwihVueJS
t
AnInt
egrat
ion
Handbook
Laravel with VueJS: An Integration Handbook
Table of Contents
Introduction ................................................................................................... 1
Middleware ..................................................................................................... 16
PAGE | i
Laravel with VueJS: An Integration Handbook
PAGE | ii
Laravel with VueJS: An Integration Handbook
Introduction
Laravel is one of the most used frameworks for backend application development. It works
on the MVC architecture to deliver highly advanced web applications. But just keeping
up with Laravel doesn’t give the application required front end dynamics, so a developer
requires some other frontend tool to make interfaces of the application vibrant and eye-
catching – that is where Vue.JS comes in.
This e-book will cover its usage with Laravel in detail and will demonstrate few integration
techniques for creating composable Laravel interfaces.
This e-book is all about getting started with Vue.JS, learning its cores and implementation
in Laravel applications. It covers detailed overview of how to begin with Vue.JS, giving
users the first hand knowledge of its core usage. Each topic is covered in detail, and is
packed with the information you need to know for being a front-end master.
The e-book covers a lot of information to get you up and running with a basic Vue.JS
configuration and an overall understanding of how user interfaces are structured in Laravel.
PAGE | 1
Laravel with VueJS: An Integration Handbook
creating front-end applications; and for those who need better understanding of the tools
to solve the increasingly common problem of structuring complex front-end applications.
• The first chapter illustrates the basic configuration of Vue.JS with Laravel, getting
started with simple steps for building a Laravel application with Vue.JS.
• Meanwhile the second chapter briefs pagination setup in Laravel using Vue pagination.
Hence giving readers a first hand practical knowledge of working with Vue in Laravel
projects, and implementing desired techniques to optimize the application’s front-end.
PAGE | 2
Laravel with VueJS: An Integration Handbook
Chapter 1.
Create a Laravel
Vue Single Page
App in Under
an Hour
PAGE | 3
Laravel with VueJS: An Integration Handbook
This combination results in fast, secure and impressive applications that need minimum
time to go from ideation to final code review. The support for Vue.js means that Laravel
developers can use Vue components easily within their apps without wasting time in writing
integrations for the components. To demonstrate the support, We have decided to create
a single page app in Laravel with a Vue.js powered front-end.
Prerequisites
For the purpose of this tutorial, We 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 ensure that we don’t get distracted by server level issues, we have 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 up
for an account.
PAGE | 4
Laravel with VueJS: An Integration Handbook
Bower
Bower is another dependency management tool used to manage front-end (HTML/JS/
CSS) packages/dependencies. A developer can download it through NPM.
Run the following commands to verify that NodeJS and NPM are indeed installed.
nodejs -v
npm -v
Now, let’s build a basic post app, where anyone can write a post. The posts will not be
saved anywhere because the app will focus on the front-end exclusively.
PAGE | 5
Laravel with VueJS: An Integration Handbook
Create post_controller.js
This app is developed in AngularJS and this is the controller for the app. Using the angular
module, we have created an app, from which we have created a controller (that is a class
as well). Do note that we have declared one function and one variable (var pc = this; this is
the a handle which is used to access the class itself.).
These functions and variables can be directly called from the HTML code:
• The post_list variable stores all the posts. We will bind it to an HTML element later, so
that any changes to this list will result in instantaneous results in the UI.
• addPost function reads the post from the post_text (which will be passed from the
HTML form) and appends it to the post_list.
PAGE | 6
Laravel with VueJS: An Integration Handbook
Update index.html
<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs angularjs/1.5.7/
angular.min.js”></script>
<script src=”angular/post_controller.js”></script>
</head>
<body>
<div ng-app=”PostApp”>
<div ng-controller=”PostController as pc”>
<form ng-submit=”pc.addPost()”>
<input type=”text” ng-model=”pc.post_text” size=”30”
placeholder=”New post...”>
<input class=”btn-primary” type=”submit” value=”add”>
</form>
<p> Total posts: {{ pc.post_list.length }} </p>
<li class=”animated flash” ng-repeat=”post in pc.post_list”>
<p>{{ post }}</p>
</li>
</div>
</div>
</body>
</html>
PAGE | 7
Laravel with VueJS: An Integration Handbook
• ng-model=”pc.post_text”: This variable maps the text within the input box with the
post_text variable in the addPost function, defined in the js file.
• {{ pc.post_list.length }}: The “post_list” variable is being directly read by PostController
class to calculate the length to display.
• ng-repeat=”post in pc.post_list”: This directive will loop through each of the post in
the post_list variable so that we can display them using the just created post
• {{ post }}: Variable provided by the loop discussed above.
NPM
Make sure you are in the <app_name>/public_html mode and run the following commands:
npm init
npm install --save bower
npm list
• The first command initializes NPM in the project. Basically, this creates a json file,which
will hold a list of all the dependencies.
• The second command installs bower. The –save switch adds the bower package to the
json file created with the first command
• The third command lists the currently installed dependencies. This list should be similar
to the packages listed within the json file.
•
The idea is that anyone runs the project can simply get things going by running the
command:
npm install
This will install all of the dependencies listed in the package.json file.
PAGE | 8
Laravel with VueJS: An Integration Handbook
Bower
At this point, you will have access to the bower binary inside node_modules directory. Run
the following commands.
├── animate.css#3.5.2
└─┬ bootstrap#3.3.7 (latest is 4.0.0-alpha.3)
└── jquery#3.1.0
• The first command initializes bower in the directory just as with “npm”. A “json” file will
be created which will hold bower dependencies.
• The Second and third commands install two dependencies which we’ll use to spice up
our app. The “–save” switch tells bower to store these dependencies in the “json” file.
As with NPM, the “bower.json” file will be used by others to automatically install
dependencies from your project using:
> bower install
PAGE | 9
Laravel with VueJS: An Integration Handbook
Also, replace:
with:
Reload the page, and add a few posts. The changes should be evident (newly added posts
will flash for a couple of seconds. The Submit button will be Blue). This was not really
impressive, but the point was to show how easy it is to install and manage dependencies
using bower and NPM. For a big project, NPM and bower are really invaluable.
Launch a new PHP Cloudways app and clone your project into the directory naming as
<app_name>/public_html using either the SFTP access or via the Git Deployment feature
PAGE | 10
Laravel with VueJS: An Integration Handbook
Finally, navigate to your project’s public_html directory and just run the following command:
If your project has a package.json file, all dependencies will be automatically installed. If
the project also has a bower.json file, then you can run the following command to see if
bower was installed through NPM.
Finally, you may need to recheck your includes and confirm the paths to the dependencies.
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.
Now, open the terminal and navigate to the root of the newly created Laravel project and
generate a new migration to create task table with the following commands:
PAGE | 11
Laravel with VueJS: An Integration Handbook
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:
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
PAGE | 12
Laravel with VueJS: An Integration Handbook
Laravel provides default user authentication where 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:
Create task model because we will handle database operations through Laravel Eloquent.
We 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:
Now, 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’,
PAGE | 13
Laravel with VueJS: An Integration Handbook
‘user_id’,
‘description’,
];
}
<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
/**
* Show the form for creating a new resource.
PAGE | 14
Laravel with VueJS: An Integration Handbook
*
* @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
PAGE | 15
Laravel with VueJS: An Integration Handbook
* @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
PAGE | 16
Laravel with VueJS: An Integration Handbook
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.
$this->validate($request, [
‘name’ => ‘required|max:255’,
‘description’ => ‘required’,
]);
PAGE | 17
Laravel with VueJS: An Integration Handbook
$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 sets the application URL and the controller method for the URL. Routes are located
inside the file named as route/web.php and contains the following code:
Route::get(‘/home’, ‘HomeController@index’)->name(‘home’);
Route::resource(‘/task’, ‘TaskController’);
Task.vue:
<template>
PAGE | 18
Laravel with VueJS: An Integration Handbook
<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
directory 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:
PAGE | 19
Laravel with VueJS: An Integration Handbook
Now open the file home.blade.php located inside the /resources/views/ directory and
update it as follows:
@extends(‘layouts.app’)
@section(‘content’)
<task></task>
@endsection
<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”>
PAGE | 20
Laravel with VueJS: An Integration Handbook
PAGE | 21
Laravel with VueJS: An Integration Handbook
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class=”form-group”>
<label for=”names”>Name:</label>
<input type=”text” name=”name” id=”name”
placeholder=”Task Name” class=”form-control”
PAGE | 22
Laravel with VueJS: An Integration Handbook
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 -->
PAGE | 23
Laravel with VueJS: An Integration Handbook
<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>
PAGE | 24
Laravel with VueJS: An Integration Handbook
<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 => {
PAGE | 25
Laravel with VueJS: An Integration Handbook
});
}
},
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 = [];
PAGE | 26
Laravel with VueJS: An Integration Handbook
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”);
PAGE | 27
Laravel with VueJS: An Integration Handbook
})
.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
When you will run the final application in the browser following output will be generated
PAGE | 28
Laravel with VueJS: An Integration Handbook
Chapter 2.
Set up Easy Vue
Pagination for
Laravel Projects
PAGE | 29
Laravel with VueJS: An Integration Handbook
Both Laravel paginate and Vue.js are popular options for adding functionality to Laravel
projects. The good part is that it is quite easy to integrate Vue.js into Laravel code. The
process is very similar to using jQuery in the code. Just include it in the body tag and you
are good to go.
In this chapter, we will demonstrate how to create simple Laravel pagination, and also how
to perform Vue pagination in Laravel 5.5.
Prerequisites
For the purpose of this tutorial, we assume that you have a Laravel application installed on
a web server. Our setup is:
• Laravel 5.5
• PHP 7.1
• MySQL
• Node.js with NPM
Server level issues can mar your learning experience. To avoid these issues, it’s better to
use managed Laravel web hosting on Cloudways. Cloudways offers a great development
stack and takes care of all server level problems. You can try out Cloudways for free by
signing for an account.
PAGE | 30
Laravel with VueJS: An Integration Handbook
In the previous chapter, we have learnt how to install Node.js with NPM, setup database
configuration and migrations for the tables. Here, the step remains same, therefore, we will
begin with creating the model factory.
We will create a model-factory by typing the following commands in the SSH terminal:
<?php
use Faker\Generator as Faker;
$factory->define(App\Post::class, function (Faker $faker) {
return [
‘title’ => $faker->sentence,
‘body’ => $faker->realText(rand(100, 676)),
‘cover_pic’ => $faker->imageUrl()
];
});?>
<?php
use Faker\Generator as Faker;
/*
|---------------------------------------------------------------------
| Model Factories
|---------------------------------------------------------------------
|
PAGE | 31
Laravel with VueJS: An Integration Handbook
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application’s database.
|
*/
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
‘name’ => $faker->name,
‘email’ => $faker->unique()->safeEmail,
‘password’ => $password ?: $password = bcrypt(‘secret’),
‘remember_token’ => str_random(10),
];
});
Database Seeder
Database Seeder is a very helpful tool that Laravel provides for database management. The
tool adds sample data to the databases automatically via the database seeding process.
Create a file named Databaseseeder.php and add the following code to the file:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
PAGE | 32
Laravel with VueJS: An Integration Handbook
{
factory(App\Post::class, 40)->create();
$this->command->info(‘seeding done...’);
}
}
Create Model
Create a file named as Post.php and paste the following code in it:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
It is time to create the controller. For this, create PostController inside the Controllers
folder and add an index method to return the paginated records:
<?php
namespace App\Http\Controllers;
use App;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
PAGE | 33
Laravel with VueJS: An Integration Handbook
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::paginate(3);
$response = [
‘pagination’ => [
‘total’ => $posts->total(),
‘per_page’ => $posts->perPage(),
‘current_page’ => $posts->currentPage(),
‘last_page’ => $posts->lastPage(),
‘from’ => $posts->firstItem(),
‘to’ => $posts->lastItem()
],
‘data’ => $posts
];
return response()->json($response);
}
We will now modify the welcome.blade.php file for creating the view of Vue pagination in
Laravel. Open the file and paste the following code in the file:
<!doctype html>
<html lang=”{{ app()->getLocale() }}”>
<head>
<meta charset=”utf-8”>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-
scale=1”>
<title>Laravel</title>
<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/
PAGE | 34
Laravel with VueJS: An Integration Handbook
bulma/0.6.2/css/bulma.min.css”>
<!-- Fonts -->
<link href=”https://fonts.googleapis.com/css?family=Raleway:100,600”
rel=”stylesheet” type=”text/css”>
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: ‘Raleway’, sans-serif;
font-weight: 100;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
PAGE | 35
Laravel with VueJS: An Integration Handbook
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 12px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class=”container” id=”app”>
<div class=”box”>
<article>
<div class=”content” v-for=”post in posts”>
<h1>
@{{ post.title }}
</h1>
<p>
@{{ post.body }}
</p>
</div>
</article>
<pagination v-if=”pagination.last_page > 1” :pagination=”pagination”
:offset=”5” @paginate=”fetchPosts()”></pagination>
</div>
PAGE | 36
Laravel with VueJS: An Integration Handbook
</div>
<script src=”http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.js”></
script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.7.0/
vue-resource.js”></script>
<script src=”{{ asset(‘js/app.js’) }}”></script>
</body>
</html>
For displaying the data, we will modify the routes/web.php file with the following code:
<?php
Route::get(‘/’, function () {
return view(‘welcome’);
});
Route::resource(‘posts’, ‘PostController’); ?>
PAGE | 37
Laravel with VueJS: An Integration Handbook
When you will run the final application in the browser following output will be generated
PAGE | 38
Laravel with VueJS: An Integration Handbook
Summarizing the above, the e-book is divided into two chapters covering the integration
of Vue.js with Laravel first and then setting up Vue pagination in the next.
The first chapter gives a brief insight how to combine Laravel and Vue.js into an effective
front-end and back-end process. It explores the detailed process how to implement Vue.js
with Laravel for building better front-end applications.
While the second chapter explains Vue.js & Laravel integration bit more practically, showing
how to implement Pagination process in a Laravel application using Vue.js.
Overall, it’s a complete e-book for both beginners and intermediate developers to get
acquaintance of the front-end technology and optimization of app interfaces with it. The
e-book is intended to give practical knowledge of Vue.js which is largely getting adopted
by the front-end community for building dynamic application interfaces.
PAGE | 39
AboutCl
oudways
AManagedCl
oudHost
ingPl
atf
orm Wher
eTeamsCan
Bui
ld,Depl
oy,Scal
e&ManagePhenomenalWeb
Appl
icat
ions
Cl
oudwaysLt
d. Connectwi
thUs
52Spri
ngval
e,PopePi
usXI
ISt
reet
,
Most
aMST2653,Malta
j
oin@cl
oudways
.com www.
cloudways
.com