Laravel 8 Vue Js Infinite Scroll Load More Tutorial

The detailed and step-by-step guide on infinite page scroll in Laravel Vue js, throughout this laravel vue js infinite scroll tutorial, will tell you how to integrate infinite page scroll with pagination in the laravel app using the vue js component mechanism.

For this Laravel Vue JS infinite scroll example, we will need, a laravel app, database connected to laravel, dummy or real records presented in the database, and Laravel vue UI configured in laravel project.

Moreover, we will use the vue-infinite-loading and vue-resource packages to create infinite page scroll in laravel and vue.

We will show you how to set up your app with the above configuration and profoundly understand the nuances of this Vue-infinite-loading example.

Why need this Laravel infinite scroll tutorial, well? Due to the infinite scroll, we can show the content to the user unless the content or data is not finished. In modern applications, this technique is used to keep the user engaged and display endless information.

Laravel 8 Vue Infinite Load More Example

  • Step 1: Download New Laravel App
  • Step 2: Add Database Information in ENV
  • Step 3: Run Migration and Seed Test Data
  • Step 4: Configure Controller
  • Step 5: Add Routes in Laravel
  • Step 6: Implement Infinite Load More in Laravel
  • Step 7: View App in Browser

Download New Laravel App

If the laravel project is not created yet, run the provided command. If already done, then jump on to the other instruction.

composer create-project laravel/laravel laravel-vue-blog --prefer-dist

Add Database Information in ENV

The proliferation of this tutorial requires making a connection between laravel and the database, thus add the database details in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=

Run Migration and Seed Test Data

Next, run the migration to insert the default users table into the database.

php artisan migrate

Now, execute the php artisan tinker command from the console.

php artisan tinker

Immediately after run the provided command, it will generate the test data and seed the users’ data into the database.

User::factory()->count(300)->create()

Configure Controller

Loading the view template in the browser, fetching the users’ data from the database is what we need to do now, so first create the new controller, name it UserController.

php artisan make:controller UserController

Above command generated a controller file, add the following code in app/Http/Controllers/UserController.php file.

<?php

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


class UserController extends Controller
{
    public function index(Request $request)
    {
        return view('welcome');
    }

    public function getUsers()
    {
        $items = User::orderBy('id')->paginate(10);
        return response()->json($items);
    }
}

Add Routes in Laravel

Next, add routes; these routes will show blade view in the viewport and make GET request to render the users collection.

Update code in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Set Up Laravel UI Vue

Next, install laravel/ui; this library is the primary locus of Bootstrap and Vue scaffolding; install this profound package in the laravel app.

composer require laravel/ui

After installing the laravel/ui package, install the vue frontend scaffolding with the help of artisan command.

php artisan ui vue

Before we start compiling our CSS, install the important dependencies using the Node package manager.

npm install

Start the compilation process using the below command.

npm run watch

Implement Infinite Load More in Laravel

Next, install the vue-infinite-loading package into laravel vue app; this helps build infinite page scroll load more in laravel vue.

npm i vue-infinite-loading

Next, install the vue-resource package in laravel vue app.

npm i vue-resource

Now, head over to resources/js/components folder, create UserComponent.vue, after that update the provided code in
resources/js/components/UserComponent.vue file.

<template>
    <div class="container mt-5 text-center" style="max-width: 450px">
        <h2 class="mb-5 text-center">Laravel Vue Js Ininfite Scroll Page Load More Demo</h2>
        <div class="card mb-3" v-for="user in USERS" :key="user.id">
            <div class="card-body">
                <h5 class="card-title">{{user.name}}</h5>
                <p class="card-text">{{user.email}}</p>
            </div>
        </div> 
        <infinite-loading @distance="1" @infinite="loadMoreData"></infinite-loading>
    </div>    
</template>

<script>
    export default {
        data() {
            return {
                USERS: [],
                page: 1,
            };
        },
        methods: {
            loadMoreData($state) {
                this.$http.get('/users?page=' + this.page)
                    .then((response) => {
                        return response.json();
                    }).then(response => {
                        $.each(response.data, (key, v) => {
                            this.USERS.push(v);
                        });
                        $state.loaded();
                    });
                this.page = this.page + 1;
            },
        },
    }
</script>

Next, get into the resources/js/app.js; inside here, add the vue components using Vue.component() method, also import the VueResource and vue-infinite-loading modules here.

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

import VueResource from 'vue-resource';
Vue.use(VueResource);

Vue.component('user-load-more-component', require('./components/UserComponent.vue').default);
Vue.component('InfiniteLoading', require('vue-infinite-loading'));

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

We need to update the resources/views/welcome.blade.php, this file will load the vue component in the laravel blade view file, aslo show the users data.

@extends('layout.app')
@section('content')

<div>
    <user-load-more-component></user-load-more-component>
</div>

@endsection

Next, move towards resources/views folder, inside here create layout folder then create app.blade.php layout file.

Update code in resources/views/layout/app.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">
    <meta name="csrf-token" value="{{ csrf_token() }}" />
    <title>Laravel Vue JS Infinite Scroll Load More Example</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>

<body>
    <div id="app">
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>

</html>

View App in Browser

The desired feature has been developed, now check the functionality in the browser with the below command and the url.

php artisan serve
http://127.0.0.1:8000/home

Laravel Vue Js Load More

Conclusion

Throughout this tutorial, we have thrown light on every aspect needed to create infinite page scroll page load more functionality in the laravel vue app. Not just that, we understood the nuances eloquently. We comprehended creating a new laravel vue app, setting up the database, seeding the database with dummy data, incorporating vue in laravel, adding laravel vue UI, and getting data from the database.

Eventually, we accumulated everything to build Laravel Vue JS infinite page scroll feature to load more data on the page.