0% found this document useful (0 votes)
70 views

Laravel Vuejs Handbook

Uploaded by

renas2h.h
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Laravel Vuejs Handbook

Uploaded by

renas2h.h
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Lar

avelwihVueJS
t
AnInt
egrat
ion
Handbook
Laravel with VueJS: An Integration Handbook

Table of Contents
Introduction ................................................................................................... 1

Chapter 1: Create a Laravel Vue Single Page App ............................. 3

Install Node.js with NPM ................................................................................... 5

Configure the Database .................................................................................. 11

Create the Migrations ....................................................................................... 11

Run the Migration ........................................................................................... 12

Setup User Authentication ............................................................................. 13

Create Task Model and Task Controller ........................................................ 13

The Code for Controller ................................................................................. 14

Middleware ..................................................................................................... 16

Create the Method ......................................................................................... 17

Update Method ............................................................................................... 17

Delete Method ............................................................................................... 18

Route set up in Laravel SPA ........................................................................... 18

Create Vue.js Components ............................................................................ 18

Compile Assets .............................................................................................. 19

PAGE | i
Laravel with VueJS: An Integration Handbook

Calling in the View ......................................................................................... 20

Create Update & Delete in Task.vue ............................................................ 20

Chapter 2: Set up Easy Vue Pagination for Laravel Projects ........ 29

Create model-factory ...................................................................................... 31

Database Seeder ............................................................................................ 32

Create Model .................................................................................................. 33

Create the Controller ...................................................................................... 33

Create the View ...............................................................................................34

Build the Route ............................................................................................... 37

Ending of the e-Book ............................................................................... 38

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.

Vue.JS is an open-source JavaScript framework for developing highly customized


interfaces. Since the framework’s initial release, it has experienced an unprecedented
boom and won the laurels of huge community of front-end developers. Moreover, its high
flexibility with Laravel has given it a much wider exposure and reason to use in developing
full-fledged advanced web applications.

This e-book will cover its usage with Laravel in detail and will demonstrate few integration
techniques for creating composable Laravel interfaces.

What This e-book Is All About

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.

Who Should Read This e-book?

This e-book covers detailed and comprehensive explanation of Vue.JS implementation


with Laravel. Hence, it is for both beginners and intermediate developers to master the
process. The content in this e-book is for developers who have no or some experience in

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.

A Quick Navigation of the e-book

The book is divided into two chapters:

• 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

Create a Laravel Vue Single Page


App in Under an Hour
Laravel has become the most popular choice among developers for building 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 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

Install Node.js with NPM


NodeJS
NodeJS is a server-side JS environment for web apps. For those who want to start writing
server-side code using JS instead of PHP, Python, and Ruby, this is a great news.

What is NodeJS Package Manager (NPM)?


NodeJS Package Manager (NPM) is the dependency management tool that comes with
NodeJS. NPM is to NodeJS what pip is to Python or ruby-gems is to Ruby. It makes it easy
to download and manage NodeJS modules, removing a lot of hassle for the users.

Bower
Bower is another dependency management tool used to manage front-end (HTML/JS/
CSS) packages/dependencies. A developer can download it through NPM.

Launch a New Project


Go ahead and launch a Cloudways server with a simple PHP stack application. Open the
SSH terminal and enter the master credential. Once accessing the server successfully,
change directory to the project’s public_html directory.

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

var post = angular.module(‘PostApp’, []);


post.controller(‘PostController’, function() {
var pc = this;
pc.post_list = [‘Hello World’, ‘Testing’]; //Class variable
pc.addPost = function(){
pc.post_list.push(pc.post_text)
pc.post_text = “”
};
});

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.

Focus on Building PHP/Laravel Apps


Leave Server Management to Cloudways

GET STARTED FREE

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>

• ng-app=”PostApp”: We declared the app inside a div using this attribute.


• ng-controller=”PostController as pc”: This declares the Controller and assigns it an
alias for easy access.
• ng-submit=”pc.addPost(): This is a trigger. When the form is submitted, the addPost
function defined in the js file will be called. This call will append the post to the post_list
variable.

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.

The basic app is now complete. Let us test it out.


At this point, we will initialize NPM and NodeJS in the project’s directory.

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.

> node_modules/bower/bin/bower bower init


> node_modules/bower/bin/bower bower install bootstrap --save
> node_modules/bower/bin/bower bower install animate.css --save
> node_modules/bower/bin/bower list
bower check-new Checking for new versions of the project
dependencies...
posts public_html

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

◊ boostrap: Used to show custom themes for the UI


◊ css: Basic animation classes

• The final commands list the currently installed dependencies.

As with NPM, the “bower.json” file will be used by others to automatically install
dependencies from your project using:
> bower install

Add the following lines within the head tags in index.html:

PAGE | 9
Laravel with VueJS: An Integration Handbook

<link rel=”stylesheet” type=”text/css” href=”bower_components/animate.


css/animate.css”>
<link rel=”stylesheet” type=”text/css” href=”bower_components/bootstrap/
dist/css/bootstrap.min.css”>
<link rel=”stylesheet” type=”text/css” href=”bower_components/bootstrap/
dist/css/bootstrap-theme.min.css”>
<script src=”bower_components/jquery/dist/jquery.min.js”></script>
<script src=”bower_components/bootstrap/dist/js/bootstrap.min.js”></
script>

Also, replace:

<li ng-repeat=”post in pc.post_list”>

with:

<li class=”animated flash” ng-repeat=”post in pc.post_list”>

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.

Possible Workflow Strategy

• Commit json and package.json using your preferred SCM.


• Ignore bower_components and node_modules
• After cloning a project, users should run npm install and later bower install

Existing PHP Projects

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

that Cloudways offers.

Finally, navigate to your project’s public_html directory and just run the following command:

<app_name>/public_html> npm install

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.

<app_name>/public_html> npm list

If it was, go ahead and install bower dependencies.

<app_name>/public_html> node_modules/bower/bin/bower install

Finally, you may need to recheck your includes and confirm the paths to the dependencies.

That’s it! You’re good to go.

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

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:

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

PAGE | 12
Laravel with VueJS: An Integration Handbook

Setup User Authentication

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:

php artisan make:auth

Create Task Model and Task Controller

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:

php artisan make:model Task -r

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’,
];
}

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.

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

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

PAGE | 16
Laravel with VueJS: An Integration Handbook

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.

$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 set up in Laravel SPA

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

Create Vue.js Components

Create a new file for Task component within /resources/assets/js/components/ folder


named Task.vue and add following sample code:

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

npm run dev

Calling in the View

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

Create Update & Delete in Task.vue

The Task component is located within /resources/assets/js/components/ directory 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”>

PAGE | 20
Laravel with VueJS: An Integration Handbook

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

PAGE | 21
Laravel with VueJS: An Integration Handbook

</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”

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

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

PAGE | 23
Laravel with VueJS: An Integration Handbook

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>

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 = [];

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.

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

Set up Easy Vue Pagination for


Laravel Projects
Pagination is a method for dividing content into several pages and creating appropriate
layouts for better and organized presentation. Pagination is an essential requirement for
blogs, websites that have their front-pages to sufficiently showcase the most important
posts. In this case Laravel pagination or Vue pagination is perfect choice for developers.

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.

Create Model Factory

We will create a model-factory by typing the following commands in the SSH terminal:

php artisan make:factory PostFactory --model=Post


php artisan make:factory UserFactory --model=User

Next, simply edit the Post factory:

<?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()
];
});?>

Next, edit User Factory:

<?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
{
//
}

Create the Controller

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

Create the View

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>

Build the Route

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’); ?>

Focus on Building PHP/Laravel Apps


Leave Server Management to Cloudways

GET STARTED FREE

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

Ending of the e-book

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

You might also like