Laravel 8 Ajax Pagination Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello Dev’s
Welcome back again. Today in this tutorial, I will show you how to create jquery ajax pagination in laravel 8 application. We will show you it step by step simple Laravel 8 Ajax Pagination.

Pagination is a very basic and important requirement of our every project. As like as Admin Panel, ERP or back-end Panel also front-end. Pagination helps us to load a few records every time in our application. On that way can’t broke web page due of lots of data. If we are making pagination and do it using ajax then it a better way of solution. Ajax Pagination will load only once from your table data instead of the whole page.

So ajax pagination is a very helpful for real life big project. In this tutorial, I will simply create “items” table by using migration command and add also some dummy records. After that, i will create one route on route file for display view and write code jquery ajax on my blade file. So, you have to need just follow below step and also you will get simply ajax pagination by using laravel 8.

Step 1 : Install Laravel 8

I am going from scratch. So I  require to get fresh Laravel 8 application by using bellow command, So open my terminal OR command prompt and run bellow this command:

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

Step 2: Create Table and Model

Now in this step we have to create a new migration for items table by using Laravel 8 php artisan command. So again now fire bellow command:

php artisan make:model Item

After using successfully this command we will find one new file in following path “database/migrations” and we have to put bellow code in our migration file for create new items table.

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

Read Also : How to store all record in laravel Cache?

Now simply run migration:

php artisan migrate

After successfully create “items” table we also create Item model for items, so put bellow content in item.php file:

app/Item.php

<?php
  
namespace App;
   
use Illuminate\Database\Eloquent\Model;
  
class Item extends Model
{
       
}

Step 3: Create Route

Now in this is step we just need to create routes for items listing. So open your “routes/web.php” file and add following code for route.

routes/web.php

Route::get('ajax-pagination','AjaxController@ajaxPagination')->name('ajax.pagination');

Step 4: Create Controller

Now in this step, we have to create two view file one for our layout and another one for our data. Now we have to create new controller as name AjaxController in this path “app/Http/Controllers/AjaxController.php”. After this controller will manage our all listing items and item ajax request and return response. So now put bellow content in our controller file:

app/Http/Controllers/AjaxController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Item;
  
class AjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function ajaxPagination(Request $request)
    {
        $data = Item::paginate(5);
  
        if ($request->ajax()) {
            return view('presult', compact('data'));
        }
  
        return view('ajaxPagination',compact('data'));
    }
}

Step 5: Create Blade Files

In our Last step, let’s we create ajaxPagination.blade.php on location (resources/views/ajaxPagination.blade.php) for layout and lists all items. Now put code from following code:

resources/views/ajaxPagination.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 AJAX Pagination Example - Codingspoint.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
  
<body>
<div class="container">
    <h1>Laravel 8 AJAX Pagination Example - Codingspoint.com</h1>
    <div id="tag_container">
           @include('presult')
    </div>
</div>
  
<script type="text/javascript">
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            }else{
                getData(page);
            }
        }
    });
    
    $(document).ready(function()
    {
        $(document).on('click', '.pagination a',function(event)
        {
            event.preventDefault();
  
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
  
            var myurl = $(this).attr('href');
            var page=$(this).attr('href').split('page=')[1];
  
            getData(page);
        });
  
    });
  
    function getData(page){
        $.ajax(
        {
            url: '?page=' + page,
            type: "get",
            datatype: "html"
        }).done(function(data){
            $("#tag_container").empty().html(data);
            location.hash = page;
        }).fail(function(jqXHR, ajaxOptions, thrownError){
              alert('No response from server');
        });
    }
</script>
  
</body>
</html>

resources/views/presult.blade.php

<table class="table table-bordered">
    <thead>
        <tr>
            <th width="100px">ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($data as $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
  
{!! $data->render() !!}

Before run make sure that you have some dummy data on your items table.if not then before run this example please put some data. Then we are full ready to run our example. So now run bellow command for quick run:

php artisan serve

Now we can open bellow URL on our browser for load project:

http://localhost:8000/ajax-pagination

hope it can help you…

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →