This website uses cookies

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

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

Set up Easy Vue Pagination for Laravel Projects

Updated on December 20, 2021

6 Min Read
vue-pagination-in-laravel

Pagination is a method for dividing content into several pages and creating appropriate layouts for better and more organized presentation. Pagination is an essential requirements for blogs, websites  who wish their front-pages to be sufficiently little to stack but then 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 very 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 Laravel pagination example, I 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 Laravel pagination example, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.1
  • MySQL
  • Node.js with NPM

Server level issues could mar your learning experience. In my case, I avoid these issues by 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.

You might also like: Enhanced Cloudways Staging Environment Is Now Available for All Users

Laravel Simple Pagination

Developing a website, pagination is the process many web developers experience on different stages. There are many ways in PHP to create simple pagination. But while creating Laravel 5 pagination, you must keep a track of few things to complete the process. These few things include Fetching and parsing data, items per page, current page, number of pages, which pages to show and different other aspects. While instead of implementing your own coding, using tried and tested package for Laravel 5 pagination is often said as a perfect practice.

Laravel has an inbuilt package called illuminate/pagination for the purpose of pagination. Further, this Laravel paginate package has not any particular dependence on any framework.

Get Maximum Web Speed With Painless Laravel Servers

Don’t Worry About the Lack in Web Performance. Our Laravel Servers Got You Covered!

Install Laravel Pagination

First, start the process by installing illuminate/pagination with Composer.

composer require illuminate/pagination

Generate Fake Data

You can use Laravel’s inbuilt package called Faker to generate dummy data for the application. Take a look below at the default composer.json of Laravel.

"require-dev": {
"filp/whoops": "~2.0",
"nunomaduro/collision": "~1.1",
"fzaninotto/faker": "~1.4",
…...

},

Now, we just need to write the 6-7 lines of code to generate the fake users’ data. Go to the database/seeds/DatabaseSeeder and add the following lines of code in it.

// DatabaseSeeder.php

/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
foreach (range(1,500) as $index) {
DB::table('users')->insert([
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt('secret'),
]);
}
}

We have first created the faker object and afterwards implemented loop through different columns of the users table, while have assigned one property at a time. So every time a loop is executed, new dummy data is generated and is integrated with the particular columns. This is how fake data for each individual user is generated. Just paste the following command to create the fake data.

php artisan db:seed

Now as you can see, there are different user tables and rows are added into the database after pasting the above command. The db:seed command runs this file called DatabaseSeeder.php.

You might also like: Connect Laravel with Firebase Real-time Database

Controller

Now, go to the HomeController.php file and inside it create a function called getEmployees().

// HomeController.php

use App\Employee;

public function getEmployees()
{
$employees = Employee::paginate(15);

return view('index', compact('Employees'));
}

Routes

Next, open your web.php file and set your routes setting.

Route::get('/users', 'HomeController@getEmployees’)->name('employee');

View

Create your view file and paste the following code.
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Users Data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach($employees as $emp)
<tr>
<td>{{ $emp->id }}</td>
<td>{{ $emp->name }}</td>
<td>{{ $emp->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>

Converting Laravel Paginate Results To JSON

To convert the Laravel pagination results to JSON, the Laravel paginator result classes uses the Illuminate\Contracts\Support\JsonableInterface contract and outputs with the Json method. So it’s pretty easy to convert your pagination results to the JSON using the above method. Just paste the below code inside the web.php file.

Route::get('employee', function () {
return App\Employee::paginate(5);
})

Vue Pagination in Laravel

Steps to Create Vue Pagination in Laravel
Install Node.js with NPM
Database Configuration
Create the Migrations
Run the Migration
Create model-factory
Database Seeder
Create Model
Create the Controller
Create the View
Build the Route

Install Node.js with NPM

The first step is the installation of Node.js with NPM.

For this, first install Node.js. Next navigate to the project’s folder. Launch the terminal and then type the following command:

npm init

npm install

This command will install all the dependencies for VueJS. In addition, the command will also install laravel-mix, an API for defining webpack.

Database Configuration

The next step is the setup of MySQL database. I will also show you how to configure it for Laravel.

In the project root, you will find the .env .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_posts_table --create=posts

Next , open the migration file located in the database/migration folder and replace the up() function with the following code:

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration

{

   /**

    * Run the migrations.

    *

    * @return void

    */

   public function up()

   {

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('body');

$table->string('cover_pic')->nullable();

$table->timestamps();

});

   }

   /**

    * Reverse the migrations.

    *

    * @return void

    */

   public function down()

   {

       Schema::dropIfExists('posts');

   }

}

Run the Migration

Next, I will create the required tables in the database through the following command:

php artisan migrate

Create model-factory

Next, I 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

|--------------------------------------------------------------------------

|

| 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 in a process known as database seeding. 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()

   {

       factory(App\Post::class, 40)->create();

$this->command->info('seeding done...');

   }

}

Create Model

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

    *

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

I will now modify welcome.blade.php 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/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;

           }

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

       </div>

<script src="https://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, I will modify the routes/web.php file like this:

<?php

Route::get('/', function () {

   return view('welcome');

});

Route::resource('posts', 'PostController'); ?>

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

Q: What is VueJS Pagination?

A: Pagination is a simple feature in Vuejs that allows to arrange components with a page number. You can use in built manual method to setup pagination in Vuejs, but could also use some premade plugins to do the same. VueJs paginator is a much known plugin to perform pagination, as it provides an easy way to render data instead of using a predefined table. Using the plugin, you can easily setup pagination within minutes without going into technical details.

Q: What is Ajax pagination in Laravel?

A: Ajax pagination is very helpful in Laravel, as it helps to load your table data instead of the whole page. This shortens the load time and quickly shows up the results right from the table data.

Conclusion

Vue pagination in Laravel 5.x is incredibly easy to implement. Here is an example of how pagination with Vue and Laravel works. You should see the application in action to understand how Vue.js combines with Laravel code in order to simplify the life of the developers. Still if you have any further questions regarding Laravel Paginate and Vue.js, do leave your comments below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

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 [email protected]

×

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

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now