How to Make Infinite Scroll with Jquery Ajax in Laravel

How to Make Infinite Scroll with Jquery Ajax in Laravel
Hello everyone, back again at porkaone. On this occasion, we will learn how to use infinite scroll in Laravel. Intrigued?, let's follow the tutorial below.

Infinite scroll is a term when you reach the bottom of the page, then new data will be loaded again. Then you can scroll again to the very bottom of the page. And that happens until the existing data runs out. This is commonly used on news pages, photo stacks, homepages that contain lots of posts or any page that lists a long list down.

This technique is quite efficient, because not all data is issued at once. Web pages become much more user friendly because pages load much faster. In this tutorial, we will try to implement the infinite scroll technique in Laravel.

How to Make Infinite Scroll with Jquery Ajax in Laravel

1. Download and install Laravel version 7,8,9 or the latest version. Or you can also use an existing Laravel project. We will not discuss the installation method here. Apart from that, please set the .env file and connect to the database.

2. Run the following command to create a new Post and migration model
php artisan make:model Post -m

3. After running the command above open the migration post in the database/migrations folder and follow the script as below.

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

4. Open the Post.php file inside the app/models folder then change the contents in it as below.

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; public $fillable = ['title','description']; }

 Run the command below, to create a new table in mysql. Also make sure you have connected the .env file to the mysql database. If not done then an error will occur..
php artisan migrate

6. Open the web.php file inside the routes folder. Then add the script below.

Route::get('post', 'App\Http\Controllers\PostController@index');

7. Run the command below to create a postController
php artisan make:controller PostController

8. Then open app/Http/Controllers/PostController.php. Then edit the contents in it with the script below.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { public function index(Request $request){ $posts = Post::paginate(5); if ($request->ajax()) { $view = view('data',compact('posts'))->render(); return response()->json(['html' => $view]); } return view('post', compact('posts')); } }

9. Create a new blade file named post.blade.php in the resources/views folder. Then edit the contents in it with the script below.

<!DOCTYPE html> <html> <head> <title>Laravel infinite scroll</title> <link rel="stylesheet" href="" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <style type="text/css"> .preloader { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background-color: #fff; } .loading { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font: 14px arial; } </style> </head> <body> <div class="preloader"> <div class="loading"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> <div class="container"> <h2 class="text-center">Laravel infinite scroll Tutorial</h2> <br /> <div class="col-md-12" id="post-data"> @include('data') </div> </div> <script src=""></script> <script src="" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"> </script> <script> //when file loaded for first time, fadeout this loader $(window).load(function() { $(".preloader").fadeOut("slow"); }); </script> <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() { $('.preloader').show(); } }) .done(function(data) { $('.preloader').hide(); $("#post-data").append(data.html); }) .fail(function(jqXHR, ajaxOptions, thrownError) { alert('server not responding...'); }); } </script> </body> </html>

10. Create another blade file named data.blade.php in the resources/views folder. Then edit the contents in it with the script below.

@foreach ($posts as $post) <div> <h3><a href="">{{ $post->title }}</a></h3> <p>{{ \Illuminate\Support\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
Ok, we have passed all the stages. Next we test. run the command php artisan serve. Then access https://localhost:8000/post. If the display looks like the image below, it means you have succeeded.

Cara Membuat Infinite Scroll dengan Jquery Ajax di Laravel
Hasil Akhir

Above is a simple example of how to make an infinite scroll on a website page. Now you can make it yourself and improvise so that it fits your project needs.

Ok, that's all for this tutorial about how to make an infinite scroll in Laravel. Hopefully this short tutorial is useful. If you have something to ask, please ask directly in the comments column below. That is all and thank you.

Post a Comment