Laravel Pagination with Ajax Example

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

Today now in this tutorial, I will explain you how to create pagination in laravel application by using jquery ajax. Here we will create pagination in laravel application by using ajax. Now here i will show you step by step simple ajax pagination in laravel application.

We know that pagination helps us to load few records every time, so that way cannot break web page due to lots of data. So If we are making pagination and do it by using ajax then it is a better way. So Ajax Pagination load only our table data instead of the load whole page. We know that’s why ajax pagination is very helpful.

Here we simply create a “product” table by using migration command and then we will add some dummy records. So after that, i will create one new route for display view and then i will write code jquery ajax on blade file. So, you need to just follow below step and then you will know about simply ajax pagination in laravel application,

Here so i will give you full example of ajax pagination example step by step as like create laravel 8 project, then migration, model, route, blade file etc. So just you need to follow few steps.

Step 1 : Install Laravel 8 Application

Here i am going from scratch, So i need to get fresh Laravel application by using bellow command, So need to open your terminal OR command prompt and then run bellow command:

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

Now in this step, we need to make database configuration, we need to add following details on our .env file.

  • Database Username
  • Database Password
  • Database Name

So in .env file also available host and port details, we can configure all details as in our system, So we can put like as bellow:

following path: .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create products Table and Model

So now in this step we have to create a migration for products table by using Laravel 8 php artisan command, so need to fire bellow command:

php artisan make:model Product -m

After this command we have to put bellow code in our migration file for create products table.

following path: /database/migrations/2020_01_10_102325_create_products_table.php

<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

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

So now we require to run migration by using bellow command:

php artisan migrate

After we have to put bellow code in our model file for create products table.

following path:/app/Models/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{	
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = [
        'name',
    ];
}
Step 3: Create Route

So now in this is step we need to create a new route for ajax pagination layout file

following path:/routes/web.php

Route::get('pagination-ajax','AjaxPaginationController@ajaxPagination')->name('ajax.pagination');
Step 4: Create Controller

Now here in this step now we should create a new controller as name AjaxPaginationController, So then need run bellow command for generate new controller

php artisan make:controller AjaxPaginationController

So now this step, this controller will manage all ajax pagination layout bellow content in controller file. following file path

following path:/app/Http/Controllers/AjaxPaginationController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class AjaxPaginationController extends Controller
{
  /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
  public function ajaxPagination(Request $request)
  {
    $products = Product::paginate(5);
  
    if ($request->ajax()) {
        return view('presult', compact('products'));
    }
  
    return view('ajaxPagination',compact('products'));
  }
}
Step 5: Create Blade Files

So good’s now we are in Last step, so now let’s create a new balde file as ajaxPagination.blade.php (resources/views/ajaxPagination.blade.php) for layout and then it lists all product code here and then put following code

following path:/resources/views/ajaxPagination.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6 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 class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <div class="card-header">
                    <h5>Laravel 6 Ajax Pagination Example - CodsingsPoint.com</h5>
                </div>
                <div class="card-body" id="tag_container">
                   @include('presult')
                </div>
            </div>
        </div>
    </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 ($products as $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
{!! $products->render() !!}

So now we have some dummy data on our products table ,so before run this example. Now we are ready to run our example so need to run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/pagination-ajax

Read Also : PHP AngularJS CRUD with Search and Pagination Example From Scratch

thank you for read .I hope it can help you.Also you can follow us on Facebook.

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 →