Laravel 8 infinite scroll using ajax

how to show more data on page scroll using ajax in laravel 8

Posted by Luke Beeno on January 3, 2022

Laravel 8 infinite scroll using ajax

how to show more data on page scroll using ajax in laravel 8

Posted by Luke Beeno on January 3, 2022

In this lesson you will be shown how to load data continuously as you scroll using ajax in Laravel 8.

Step 1. Create Laravel project

composer create-project laravel/laravel scroll-load-example

Step 2. Connect to database

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

Step 3. Create Migration, Model and Controller by executing command

php artisan make:model Student -mc

Step 4. Edit database migration file

Go to "database/migration" and edit the file create_students_table.

public function up()
{
  Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->bigInteger('id_badge');
    $table->timestamps();
  });
}

Step 5. execute command

PHP artisan migrate

Step 6. Edit model file

Go to "app/models" and edit the file Student.

/**
 * The attributes that are not mass assignable.
 *
 * @var array
 */
protected $guarded = [
    'id',
];

/**
 * Fillable fields for a Profile.
 *
 * @var array
 */
protected $fillable = [
   'name',
   'id_badge'
];

Step 7. Create and edit factory file

execute command:

php artisan make:factory StudentFactory --model=Student

Go to "database/factories" and edit the file StudentFactory.

public function definition()
{
  return [
    'name' => $this->faker->name(),
    'id_badge' => $this->faker->randomDigit
  ];
}

Step 8. Populate database

Execute command:

php artisan tinker

Execute command in tinker:

App\Models\Student::factory()->count(100)->create()

Step 9. Create route

Go to "routes" and edit the file web.php.

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

/*
|--------------------------------------------------------------------------
| 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('/',[StudentController::class,'loadOnScroll']);

Step 10. Edit controller file

Go to "app/Http/Controllers" and edit the file StudentController.php.

Add this method:

public function loadOnScroll(Request $request)
{
   $posts = Student::paginate(10);
   if($request->ajax()){
       $view = view('student-data',compact('posts'))->render();
       return response()->json(['html'=>$view]);
   }
   return view('load-students', compact('posts'));
}

Step 11. Create views outlined in StudentController

Go to "resources/view" and create the file display-students.blade.php and student-data.blade.php.

display-students.blade.php below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="//cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css">
    <title>Wecode101 infinite scroll tutorial</title>
</head>
<body>
<div class="container">
    <h3 class="text-center mt-5">Laravel 8 infinite scroll using ajax</h3>
    <div id="post">
        <!-- include student-data file here -->
        @include('student-data')
    </div>
    <div class="load-data text-center" style="display:none">
        <i class="mdi mdi-48px mdi-spin mdi-loading"></i> Loading ...
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<!-- script ajax that enable infinite scroll -->
<script>
    function loadMoreData(page)
    {
        $.ajax({
            url:'?page=' + page,
            type:'get',
            beforeSend: function()
            {
                $(".load-data").show();
            }
        })
            .done(function(data){
                if(data.html == ""){
                    $('.load-data').html("No more Posts Found!");
                    return;
                }
                $('.load-data').hide();
                $("#post").append(data.html);
            })
            // Call back function
            .fail(function(jqXHR,ajaxOptions,thrownError){
                console.log("Server not responding.....");
            });

    }
    //function for Scroll Event
    var page =1;
    $(window).scroll(function(){
        let val = $(window).scrollTop() + $(window).height();
        let rnd = Math.round(val);

        if(rnd >= $(document).height()){
            page++;
            loadMoreData(page);
        }
    });
</script>
</body>
</html>

student-data.blade.php below:

@foreach($posts as $post)
    <div class="col-md-4 mb-3" >
        <div class="card">
            <div class="card-header">
                Students
            </div>
            <div class="card-body">
                <table class="table">
                    <tr>
                        <th>Name</th>
                        <td>:</td>
                        <td>{{$post->name}}</td>
                    </tr>
                    <tr>
                        <th>Student ID</th>
                        <td>:</td>
                        <td>{{$post->id_badge}}</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
@endforeach

Now start the server and open the browser, you should see infinite scroll in action.

To download this tutorial go to https://github.com/wecode101/how-to-show-more-data-on-page-scroll-using-ajax-in-laravel-8

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question