Laravel 8 Ajax Pagination Example

Laravel 8 Ajax Pagination Example

Hi Men,

In this blog, I can provide an explanation for you the way to create jquery ajax pagination in laravel eight, we will create ajax pagination in laravel 8. i will show a little by little easy ajax pagination in laravel 8.

A pagination helps us to load few records every time, that way cannot broken net web page due to masses of information. in case you are making pagination and do it the use of ajax then it a better way. Ajax Pagination load most effective your table facts rather than the entire page. So ajax pagination is very useful.

We simply create "product" table the use of migration command and add a few dummy records. After that, we are able to create one direction for display view and write code jquery ajax on blade report. So, you need to simply follow beneath step and you will get virtually ajax pagination in laravel 8

Right here, I give you full example of ajax pagination instance grade by grade like create laravel eight undertaking, migration, model, direction, blade file and so forth. so that you have to just observe few steps.

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

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

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you 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

In this step we have to create migration for products table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Product -m

After this command you have to put bellow code in your 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');
    }
}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your 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

In this is step we need to create route for ajax pagination layout file

following path:/routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\AjaxPaginationController;
  
/*
|--------------------------------------------------------------------------
| 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('pagination-ajax','AjaxPaginationController@ajaxPagination')->name('ajax.pagination');
Step 4: Create Controller

here this step now we should create new controller as AjaxPaginationController,So run bellow command for generate new controller

php artisan make:controller AjaxPaginationController

now this step, this controller will manage ajax pagination layout bellow content in controller file.following fille 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

In Last step, let's create ajaxPagination.blade.php (resources/views/ajaxPagination.blade.php) for layout and lists all product code here and put following code

following path:/resources/views/ajaxPagination.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax Pagination Example </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 8 Ajax Pagination Example </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() !!}

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

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/pagination-ajax

It will help you...