Home Laravel How to implement infinite ajax scroll pagination in Laravel?

How to implement infinite ajax scroll pagination in Laravel?

by Shahriar Sagor

Today now in this post i will show you How to implement infinite ajax scroll pagination in Laravel? Sometimes We may want to see the auto load more data on page scroll on our home page or any other pages for posts, news, listing etc as like on facebook, twitter, linkedin etc. If we are implemented infinite scroll on our php application then we don’t need to give pagination and also do not need to page refresh every time when any page scroll.

So now, Today, i am going to give you a simple example of infinite scroll by using jquery ajax on page scroll in laravel 6, laravel 7 and laravel 8 any version application from scratch. Here I will use jquery scroll event for the page scroll. This example is very pretty and simple, we can customize this simply for our development.

We need to just follow the bellow few step and we will get the infinite scroll in our laravel application.

Step 1: Add Table and Model

At first we need to create new table “posts” on that way we will get all data from this table, you can use our own table but this is for example form scratch. we need to create the migration for posts table by using Laravel php artisan command, so first need to fire bellow command:

php artisan make:Model Post

After using this command we will find one file in the following path database/migrations and we need to put the bellow code in our migration file for create the posts table.

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


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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("posts");
    }
}

Ok, now we have to run migration using laravel artisan command:

php artisan migrate

app/Models/Post.php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    public $fillable = ['title','description'];
}
Step 2: Add Route

Now in this is step we need to add new route for generate view. So need to open our routes/web.php file and then add the following route.

Route::get('my-post', 'PostController@myPost');

Step 3: Create Controller

If you haven’t PostController then we should create a new controller as PostController in this path app/Http/Controllers/PostController.php. And Also Make sure we should have the posts table with some of data. This controller will manage the data and view file, so just need to put bellow content in controller file:

app/Http/Controllers/PostController.php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Post;


class PostController extends Controller
{


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


    	if ($request->ajax()) {
    		$view = view('data',compact('posts'))->render();
            return response()->json(['html'=>$view]);
        }


    	return view('my-post',compact('posts'));
    }
Step 4: Create View Files

Now in the last step, we need to create to view two file one is “mypost.blade.php” for the main view and another one for data, So at first need to create mypost.blade.php file:

resources/view/mypost.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel infinite scroll pagination-codingspoint</title>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  	<style type="text/css">
  		.ajax-load{
  			background: #e1e1e1;
		    padding: 10px 0px;
		    width: 100%;
  		}
  	</style>
</head>
<body>


<div class="container">
	<h2 class="text-center">Laravel infinite scroll pagination-CodingsPoint</h2>
	<br/>
	<div class="col-md-12" id="post-data">
		@include('data')
	</div>
</div>


<div class="ajax-load text-center" style="display:none">
	<p><img src="http://demo.codingspoint.com/plugin/loader.gif">Loading More post</p>
</div>


<script type="text/javascript">
	var page = 1;
	$(window).scroll(function() {
	    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
	        page++;
	        loadMoreData(page);
	    }
	});


	function loadMoreData(page){
	  $.ajax(
	        {
	            url: '?page=' + page,
	            type: "get",
	            beforeSend: function()
	            {
	                $('.ajax-load').show();
	            }
	        })
	        .done(function(data)
	        {
	            if(data.html == " "){
	                $('.ajax-load').html("No more records found");
	                return;
	            }
	            $('.ajax-load').hide();
	            $("#post-data").append(data.html);
	        })
	        .fail(function(jqXHR, ajaxOptions, thrownError)
	        {
	              alert('server not responding...');
	        });
	}
</script>


</body>
</html>

resources/view/data.php

@foreach($posts as $post)
<div>
	<h3><a href="">{{ $post->title }}</a></h3>
	<p>{{ str_limit($post->description, 400) }}</p>


	<div class="text-right">
		<button class="btn btn-success">Read More</button>
	</div>


	<hr style="margin-top:5px;">
</div>
@endforeach

Read Also: How to Get Table Name from Model in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like