Laravel 10 - Load More Data on Button Click using JQuery

Hello Artisan, today I'll show you Load More Data on Button Click using JQuery in our Laravel application. In this article, we'll show you how to implement a "Load More" button using jQuery and Laravel 10. By utilizing Laravel 10, we can efficiently handle loading additional data when the button is clicked. We'll use AJAX to make this process seamless and user-friendly.

In this example, we'll walk through creating a "posts" table using migration. Next, we'll build a data model for posts and a factory class to generate dummy post data. Lastly, we'll set up a route to load posts and implement a button click event using jQuery AJAX to load more data automatically. Let's follow the step-by-step process.

Table of Contents

  1. Install Laravel
  2. Database Configuration
  3. Create Model And Migration
  4. Create Factory Class
  5. Create Controller
  6. Create Route
  7. Create View File
  8. Run Laravel App

Install Laravel

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command

composer create-project laravel/laravel DataLode

Database Configuration

In this step, we need to update the .env file with the following database details:

  1. DB_USERNAME: [Your database username]
  2. DB_PASSWORD: [Your database password if you have ]
  3. DB_NAME: [Your database name]

Please ensure that you keep the formatting and spelling unchanged while making these modifications.

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

.env
DB_HOST=localhost
DB_DATABASE=db_lode
DB_USERNAME=root
DB_PASSWORD=

Create Model And Migration

here, we will create new Model and migration for adding new table posts in users table. so let's run bellow command:

php artisan make:Model Post -m

After this command you will find one file in following path "App\Models" and you have to put bellow code in your Post model.

app\Models\Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body', 'slug'
    ];
}

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table

database\migrations\2023_07_29_120847_create_posts_table.php
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Now you have to run this migration by following command:

php artisan migrate

Create Factory Class

This step demonstrates how to utilize a factory to generate dummy data that dynamically loads as the user scrolls the page:

php artisan make:factory PostFactory --model=Post

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

database\factories\PostFactory.php
<?php
    
namespace Database\Factories;
    
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;
    
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
      
    /**
     * Define the model's default state.
     *
     * @return array

     */
    public function definition(): array
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Open terminal, execute the below commands to generate the test data

php artisan tinker
Post::factory()->count(20)->create()

Create Controller

Here,we require to create new controller PostController with index method to display posts view and return data. So let's put bellow code.

app/Http/Controllers/PostController.php
<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
     
class PostController extends Controller
{
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $posts = Post::paginate(10);
  
        if ($request->ajax()) {
            $view = view('data', compact('posts'))->render();
  
            return response()->json(['html' => $view]);
        }
  
        return view('posts', compact('posts'));
    }
}

Create Route

In this is step we need to create routes for display posts and getting posts. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
   
/*
|--------------------------------------------------------------------------
| 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('posts',[PostController::class,'index'])->name('posts.index');

Create View File

In Last step, let's create posts.blade.php and data.blade.php for display posts list and put following code.

resources/views/posts.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Load More Data on Button Click using JQuery Laravel</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>
<body>

<div class="container mt-5" style="max-width: 750px">

    <h1>Load More Data on Button Click using JQuery Laravel</h1>

    <div id="data-wrapper">
        @include('data')
    </div>

    <div class="text-center">
        <button class="btn btn-success load-more-data"><i class="fa fa-refresh"></i> Load More Data...</button>
    </div>

    <!-- Data Loader -->
    <div class="auto-load text-center" style="display: none;">
        <svg version="1.1" id="L9" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
             x="0px" y="0px" height="60" viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
            <path fill="#000"
                  d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
                <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s"
                                  from="0 50 50" to="360 50 50" repeatCount="indefinite" />
            </path>
        </svg>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    var ENDPOINT = "{{ route('posts.index') }}";
    var page = 1;

    $(".load-more-data").click(function(){
        page++;
        infinteLoadMore(page);
    });

    /*------------------------------------------
    --------------------------------------------
    call infinteLoadMore()
    --------------------------------------------
    --------------------------------------------*/
    function infinteLoadMore(page) {
        $.ajax({
            url: ENDPOINT + "?page=" + page,
            datatype: "html",
            type: "get",
            beforeSend: function () {
                $('.auto-load').show();
            }
        })
            .done(function (response) {
                if (response.html == '') {
                    $('.auto-load').html("We don't have more data to display :(");
                    return;
                }
                $('.auto-load').hide();
                $("#data-wrapper").append(response.html);
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>
</body>
</html>
resources/views/data.blade.php
@foreach ($posts as $post)
    <div class="card mb-2">
        <div class="card-body">{{ $post->id }}
            <h5 class="card-title">{{ $post->title }}</h5>
            {!! $post->body !!}
        </div>
    </div>
@endforeach

Run Laravel App

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app.

php artisan serve

Now, Go to your web browser, type the given URL and view the app output.

http://localhost:8000/posts

Output

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚