Load More Data in Laravel Using Ajax jQuery

Websolutionstuff | Feb-26-2021 | Categories : Laravel PHP jQuery

In this article, we will see example of load more data in laravel using ajax jquery, In many websites, has huge content when you scroll down the page for more content at that time it will take some time to load more data. So, here we will auto-load more data on page scroll using ajax.

Many times you need to load more data on the infinity page scroll in laravel. So, we will give you an example of ajax jquery loads more data in laravel.

How to load data on scroll in laravel using ajax jquery

Step 1 – Install Laravel

Step 2 – Create Model and Migration

Step 3 – Add Route

Step 4 – Create Controller

Step 5 – Create Blade

 

Step 1 – Install Laravel

First of all, you need to install a new laravel application to load more data example if not exist

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

 

 

Step 2 – Create Model and Migration

For creating a new model and migration run the below command in your terminal.

php artisan make:model User -m

 

Now, open this file location app/database/migrations and add the following fields.

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Now, run migration for the same.

php artisan migrate

 

Step 3 – Add Route

Now, add a route for auto load more data on the page scroll example.

Route::get('user', [UserController::class, 'loadMore']);

 

 

Step 4 – Create Controller

Now, create UserController and add the below code in this controller.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use DB;

class UserController extends Controller
{
	public function loadMore(Request $request)
	{
		$users = User::paginate(10);        
		$data = '';
		if ($request->ajax()) {
			foreach ($users as $user) {
				$data.='<li>'.'Name:'.' <strong>'.$user->name.'</strong><br> Email: '.$user- >email.'</li>';
			}
			return $data;
		}

		return view('user',compact('users'));
	}
}

 

Step 5 – Create Blade

Now, create a blade file for output.

<!doctype html>
<html lang="en">
<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel 8 Load More Data using Ajax jQuery - websolutionstuff.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />   
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <style>
     .wrapper > ul#results li {
       margin-bottom: 2px;
       background: #e2e2e2;
       padding: 20px;     
       list-style: none;
     }
     .ajax-loading{
       text-align: center;
     }
  </style>
</head>  
<body>
  <h2 style="text-align: center;margin: 30px 0px">Laravel 8 Load More Data using Ajax jQuery - websolutionstuff.com</h2>
  <div class="container">
   <div class="wrapper">
    <ul id="results"></ul>
     <div class="ajax-loading"><img src="{{ asset('images/loader.gif') }}" /></div>
   </div>
  </div>
</body>
</html>
<script>
   var site_url = "{{ url('/') }}";   
   var page = 1;
   
   load_more(page);

   $(window).scroll(function() {
      if($(window).scrollTop() + $(window).height() >= $(document).height()) {
      page++;
      load_more(page);
      }
    });

    function load_more(page){
        $.ajax({
          url: site_url + "/user?page=" + page,
          type: "get",
          datatype: "html",
          beforeSend: function()
          {
            $('.ajax-loading').show();
          }
        })
        .done(function(data)
        {          
          if(data.length == 0){
          $('.ajax-loading').html("No more records!");
          return;
        }
          $('.ajax-loading').hide();
          $("#results").append(data);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError)
        {
          alert('No response from server');
        });
    }
</script>

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Autocomplete Search from Database
Laravel 9 Autocomplete Search...

In this article, we will see laravel 9 autocomplete search from the database. Using ajax autocomplete textbox in la...

Read More

Mar-14-2022

How To Replace All Occurrences Of String In Javascript
How To Replace All Occurrences...

In this article, we will see how to replace all occurrences of a string in javascript. You can use the javascript r...

Read More

Nov-07-2022

How To Validate Form In React JS
How To Validate Form In React...

In this article, we will see how to validate a form in react js. We will validate the input type email, phone numbe...

Read More

Sep-07-2022

Fixed: Class "DOMDocument" Not Found In Laravel
Fixed: Class "DOMDocument" Not...

In this article, we will see to fixed class "DOMDocument" not found in laravel. Also, class 'domdocum...

Read More

Feb-17-2023