Simple Vue.js Pagination Example with Laravel - TechvBlogs

Simple Vue.js Pagination Example with Laravel

Pagination is a method for dividing content into several pages and creating appropriate layouts for a better and more organized presentation. Pagination is an essential requirement for blogs, websites that wish their front-pages to be sufficiently little to stack but then sufficiently showcase the most important posts.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

3 years ago

TechvBlogs - Google News

Pagination is a method for dividing content into several pages and creating appropriate layouts for a better and more organized presentation. Pagination is an essential requirement for blogs, websites that 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 a perfect choice for developers.

Components are one of the most powerful features of Vue. They help you extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue's compiler attaches behavior to.

Simple Vue.js Pagination Example with Laravel - TechvBlogs

In this blog, I am going to describe how we can make pagination components using Laravel and Vue.js. Let's get started.

At first, download the Fresh Laravel app, Create a database in MySQL and edit the database credentials in the .env file and go up to your project directory using the command line, run the migration files using the command  php artisan migrate.

Now, a database is created and a users table is also created, Let's run the command  php artisan tinker and  \ App \ Models \ User :: factory (10) -> create ();  this will generate 100 random records for the user's table, Now we are going to paginate these 100 records of the user's table.

Now, Create a route inside  routes / api.php

use App\Http\Controllers\API\UserController;

Route::get('/users',[UserController::class,'index']);

In the Above routes, the first one is useful to return the user's records in JSON format.

Let's create one UserController  inside the Controllers / API directory and add an index method to return user's paginated records.

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index(){
        $users = User::paginate(10);
    	return response()->json($users);
    }
}

To see the paginated records, just hit the URL http://<url>/api/users?page=1then you can see something like this JSON formatted data.

Read Also:  How to Use Bootstrap in Your Vue.js Apps

Now we have to setup npm for our vue js. For more about npm  visit  Vue js

Run Following Command

composer require laravel/ui

Now set Vue.js as our Frontend, For this run following command

php artisa ui vue

Now npm install

npm install

Install laravel-vue-pagination

npm install laravel-vue-pagination

//or

yarn add laravel-vue-pagination

Go to your resources / js / app.js  and paste the following code

require('./bootstrap');

window.Vue = require('vue').default;

Vue.component('users', require('./components/Users.vue').default);

const app = new Vue({
    el: '#app',
});

resources / js / components / Users.vue

<template>
    <div class="container my-5">
        <div class="row justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header text-center">
                        <h3>Simple Vue.js Pagination Example with Laravel - <a href="https://techvblogs.com/?ref=scode" target="_blank">TechvBlogs</a></h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered text-center">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                    </tr>
                                </thead>
                                <tbody v-if="users && users.data.length > 0">
                                    <tr v-for="(user,index) in users.data" :key="index">
                                        <td>{{ user.id }}</td>
                                        <td>{{ user.name }}</td>
                                        <td>{{ user.email }}</td>
                                    </tr>
                                </tbody>
                                <tbody v-else>
                                    <tr>
                                        <td align="center" colspan="3">No record found.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <pagination align="center" :data="users" @pagination-change-page="list"></pagination>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import pagination from 'laravel-vue-pagination'
    export default {
        name:"users",
        components:{
            pagination
        },
        data(){
            return {
                users:{
                    type:Object,
                    default:null
                }
            }
        },
        mounted(){
            this.list()
        },
        methods:{
            async list(page=1){
                await axios.get(`/api/users?page=${page}`).then(({data})=>{
                    this.users = data
                }).catch(({ response })=>{
                    console.error(response)
                })
            }
        }
    }
</script>

<style scoped>
    .pagination{
        margin-bottom: 0;
    }
</style>

In the last step, we will update our welcome.blade.php file. in this file, we will use the app.js file and use it, so let's update.

resources / views / welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Simple Vue.js Pagination Example with Laravel - TechvBlogs</title>
        <link rel="stylesheet" type="text/css" href="{{ mix('css/app.css') }}">
    </head>
    <body>
        <div id="app">
            <users></users>
        </div>
        <script type="text/javascript" src="{{ mix('js/app.js') }}"></script>
    </body>
</html>

Now you have to run the below command to update the app.js file:

npm run dev

It'd be a good idea to follow along with the simple demo app that can be found in  this GitHub repo .

Read Also:  Laravel Livewire Crud Tutorial

If you have any queries or doubts about this topic please feel free to  contact us . We will try to reach you.

 

Comments (2)

Hassan Hassan 1 month ago

Does this method support search too ? i.e we have data search, export buttons for datatables ?

Pie Pow Pie Pow 1 year ago

Hi, do you know how to show sequence number base on each page in this case?

Comment


Note: All Input Fields are required.