How to Create Infinite Scroll Load More in Laravel 10 Vue

Last Updated on by in Laravel

This Laravel Vue JS infinite scroll tutorial explains how to create an infinite scroll or load more in the Laravel Vue JS application.

Throughout this comprehensive guide, you will find the easiest methods to build Vue Js infinite page scroll using the vue js components in the laravel project.

Infinite scrolling is a procedure that permits users to scroll through a large chunk of content with no finishing-line insight. This method utterly keeps refreshing a page when you scroll down it.

Generically, the infinite scroll is being used by most modern applications to enhance the user experience. In eCommerce sites, you can see multiple products on a single page; as you scroll through the app, more data gets loaded on the application’s view.

Using the same paradigm, we will create a small app in which we will load more multiple products, primarily when a page scroll event occurs. This way, we will show all the products using the infinite page scroll in the laravel vue js app.

Laravel 10 Vue JS Infinite Scroll or Load More Example

Let me enumerate the steps that we are going to follow for creating laravel infinite scroll or load more with vue js components.

  • Create Laravel Project
  • Add Database Details
  • Create Model and Run Migration
  • Generate Dummy Data
  • Generate and Configure Controller
  • Create Route
  • Install Laravel Vue UI
  • Install Vue Infinite Loading
  • Set Up Vue JS in Laravel
  • Test Application

Install Laravel Project

The first begins with installing the laravel project, so open the terminal and execute the following command:

composer create-project laravel/laravel laravel-vue-infinte-scroll --prefer-dist

Add Database Details

In the second step, open the .env configuration file and add the database name, username and password:

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Model and Run Migration

This step is all about ascertaining how to create a Model, equally important migrating the table into the database using migration.

So, run the command to create the Product model file:

php artisan make:model Product -m

Further, open the database/migrations/create_products_table.php file and add the table values within the migration of the product:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Open app/Http/Models/Product.php file and update the following code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'description'
    ];        
}

Right after creating and setting up the model and migration, its time to run the following command to migrate the Product table inside the database:

php artisan migrate

Generate Fake Data

First you have to create a product factory class:

php artisan make:factory ProductFactory --model=Product

Further, put the below code in database\factories\ProductFactory.php:

<?php

namespace Database\Factories;

use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;

class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'description' => $this->faker->text
        ];
    }
}

Use the tinker command on the console to generate the test data into the database:

php artisan tinker
Product::factory()->count(200)->create()

Generate and Configure Controller

Head over to the console, invoke the following command to generate a new controller:

php artisan make:controller ProductController

Open the newly generated file on this path app/Http/Controllers/ProductController.php and update the below code:

<?php

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


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

    public function fetchProducts()
    {
        $data = Product::orderBy('id')->paginate(12);
        return response()->json($data);
    }
}

Create Route

Next, create a route that will help to make the HTTP GET request and fetch the products data from the database; insert the below code in the routes/web.php file:

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/

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

Route::get('/products', [ProductController::class, 'fetchProducts']);

Install Laravel Vue UI

In this step, you need to install the laravel Vue UI package with below command:

composer require laravel/ui
php artisan ui vue

Further, execute command to install the required npm dependencies:

npm install

Install Vue Infinite Loading

In the subsequent step, install the vue-infinite-loading package with the npm command. It is a useful infinite scroll plugin for the Vue.js application.

It offers you a quick solution to implement an infinite scroll or load more features in an exorbitantly effortless manner. Here are the features this awesome plugin offers:

  • Mobile friendly
  • Internal spinners
  • 2-directional support
  • Load result message display
npm install vue-infinite-loading

Set Up Vue JS in Laravel

Create InfiniteScrollComponent.vue file in resources/js/components/ folder, add the following code in resources/js/components/InfiniteScrollComponent.vue file:

<template>
    <div> 
        <div v-for="product in Products" :key="product.id">
            {{product.name}}
        </div>
        <infinite-loading @distance="1" @infinite="handleLoadMore"></infinite-loading>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                Products: [],
                page: 1,
            };
        },
        methods: {
            handleLoadMore($state) {

                this.$http.get('/products?page=' + this.page)
                    .then(res => {
                        return res.json();
                    }).then(res => {
                        $.each(res.data, (key, value) => {
                            this.Products.push(value);
                        });
                        $state.loaded();
                    });

                this.page = this.page + 1;
            },
        },
    }
</script>

Next, Install the vue-resource package for enabling Vue single file components:

npm install vue-resource

Then, open resources/js/app.js file and register the Vue JS component:

require('./bootstrap');
window.Vue = require('vue').default;
import VueResource from 'vue-resource';

Vue.use(VueResource);

Vue.component('infinite-scroll-component', require('./components/InfiniteScrollComponent.vue').default);
Vue.component('InfiniteLoading', require('vue-infinite-loading'));

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

Further, add the vue component inside the resources/views/welcome.blade.php file:

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

<div class="container" style="margin-top:30px">
    <infinite-scroll-component></infinite-scroll-component>
</div>

@endsection

Finally, create a layout folder inside the resources/views path and also create an app.blade.php file.

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

Test Application

Lastly, you have to run the below command to compile the vue assets:

npm run watch

Open another terminal and start the laravel development server:

php artisan serve

Open browser and paste the following url on the address bar and view the app:

http://127.0.0.1:8000

Conclusion

The laravel vue js Infinite Scroll tutorial is over.

In this tutorial, we learned how to create Load More in Laravel Vue JS App using the vue-infinite-loading package.