load more data on button click in laravel | websolutioncode.com
load more data on button click in laravel | websolutioncode.com

Load more data on button click in laravel ajax

Introduction:

In web development, it’s common to have large sets of data that need to be displayed to users. Loading all this data at once can be inefficient and slow, especially when dealing with paginated content. One way to enhance user experience is to implement a Load more data on button click functionality, allowing users to retrieve additional data with the click of a button. In this article, we’ll explore how to achieve this using Laravel and AJAX.

Prerequisites:

Before you start working on the code, make sure you’ve completed the following preparations:

  1. Install Laravel on your system.
  2. Acquire a basic understanding of Laravel, including Blade templates, and JavaScript.
  3. Set up a database with the required tables and data.

Step 1: Setup Laravel Project

If you haven’t already created a Laravel project, open your terminal and run the following command:

composer create-project --prefer-dist laravel/laravel load-more-example

Navigate to your project directory:

cd load-more-example

Step 2: Create a Model and Migration

Generate a model and migration for the data you want to load. For example, let’s use a Post model:

php artisan make:model Post -m

This command will generate a migration file for the posts table. Open the migration file and define the table structure:

// database/migrations/xxxx_xx_xx_create_posts_table.php

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        // add other necessary columns
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

Step 3: Seed the Database

If you haven’t already, create a seeder for your model to populate the database with sample data:

php artisan make:controller PostController

Define the index method in the controller to fetch and return the initial set of data:

// app/Http/Controllers/PostController.php

use App\Models\Post;

public function index()
{
    $posts = Post::paginate(5);
    return view('posts.index', compact('posts'));
}

Create a Blade view to display the initial data and load more button:

<!-- resources/views/posts/index.blade.php -->

@extends('layouts.app')

@section('content')
    <div class="posts-container">
        @foreach($posts as $post)
            <div class="post">
                <h2>{{ $post->title }}</h2>
                <!-- display other post details -->
            </div>
        @endforeach

        {{ $posts->links() }}

        <div id="load-more-container">
            <button id="load-more" data-next-page="{{ $posts->nextPageUrl() }}">Load More</button>
        </div>
    </div>
@endsection

Step 5: Implement AJAX Logic

Include the necessary JavaScript libraries in your Blade layout file:

<!-- resources/views/layouts/app.blade.php -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Add a script section to handle the AJAX request:

<!-- resources/views/posts/index.blade.php -->

@section('scripts')
    <script>
        $(document).ready(function () {
            $('#load-more').on('click', function () {
                let nextPageUrl = $(this).data('next-page');
                
                if (nextPageUrl) {
                    $.ajax({
                        url: nextPageUrl,
                        method: 'GET',
                        success: function (data) {
                            $('#load-more-container').before(data);
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                }
            });
        });
    </script>
@endsection

Step 6:

Update the Controller for AJAX Requests

Modify the controller to handle AJAX requests and return data as needed:

// app/Http/Controllers/PostController.php

public function index(Request $request)
{
    $posts = Post::paginate(5);

    if ($request->ajax()) {
        return view('posts.data', compact('posts'));
    }

    return view('posts.index', compact('posts'));
}

Create a new Blade view for rendering the additional data:

<!-- resources/views/posts/data.blade.php -->

@foreach($posts as $post)
    <div class="post">
        <h2>{{ $post->title }}</h2>
        <!-- display other post details -->
    </div>
@endforeach

{{ $posts->links() }}

Step 7: Test the Application

Run your Laravel development server:

php artisan serve

Visit your application in the browser and test the “Load More” functionality.

Conclusion:

Implementing “Load More” functionality in Laravel using AJAX can significantly enhance user experience, especially when dealing with large datasets. This step-by-step guide should help you integrate this feature seamlessly into your Laravel application. Feel free to customize the code based on your specific requirements and design preferences. Happy coding!

Leave a Reply