Laravel 8 Ajax Pagination Example

May 31, 2021 . Admin

Hi Dev,

Today,I will learn you how to create jquery ajax pagination in laravel 8, we will engender ajax pagination in laravel 8. i will justify a step by step simple ajax pagination in laravel 8.

In this article pagination avails us to load few records every time, that way cannot broken web page due to lots of data. If you are making pagination and do it utilizing ajax then it a better way. Ajax Pagination load only your table data in instead of the whole page. So ajax pagination is very subsidiary.

So, we will simply and easily engender "products" table using migration command and add some dummy records. After that, we will engender one route for display view and write code jquery ajax on blade file. So, you have to just follow below step and you will get simply ajax pagination in laravel 8

Now, it's time to show you full example of ajax pagination example step by step like engender laravel 8 project, migration, model, route, blade file etc. So you have to just follow few steps.

Step 1 : Install laravel 8 Application

In first step we are going from scratch, So we need to get fresh Laravel 8 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 need 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:

Path : .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create products Table

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

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

Path : database/migrations/2021_05_29_064753_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->id();
            $table->string('name');
            $table->string('price');
            $table->text('details');
            $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
Step 3: Create Product Model
php artisan make:model Product -m

After you have to put bellow code in your model file for create products table.

Path : app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'price',
        'details',
    ];

}

Step 4: Create Route

In this is step we require to engender route for ajax pagination layout file

Path : /routes/web.php
<?php
use App\Http\Controllers\AjaxpagiController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('ajax-pagi',[AjaxpagiController::class,'index'])->name('ajax-pagi');
Step 5: Create Controller

here in this fifth step now we should engender new controller as AjaxpagiController,So run bellow command for generate new controller

php artisan make:controller AjaxpagiController

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

Path : app/Http/Controllers/AjaxpagiController.php
<?php

namespace App\Http\Controllers;

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

class AjaxpagiController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $products = Product::paginate(5);

        if ($request->ajax()) {
            return view('pagiresult',compact('products'));
        }

        return view('ajaxpagi-show',compact('products'));

    }
}

Step 6: Create Blade Files

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

Path : resources/views/ajaxpagi-show.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 8 Ajax Pagination Example - MyWebTuts.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 mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Laravel 8 Ajax Pagination Example - MyWebTuts.com</h5>
                    </div>
                    <div class="card-body" id="tag_container">
                        @include('pagiresult');
                    </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 url = $(this).attr('href');
                var page = $(this).attr('href').split('page=')[1];

                getData(page);
            });
        });

        function getData(page) {
            // body...
            $.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>
Path : resources/views/pagiresult.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 8 Ajax Pagination Example - MyWebTuts.com</title>
</head>
<body class="bg-dark">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover table-bordered">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Price</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($products as $value)
                            <tr>
                                <td>{{ $value->id }}</td>
                                <td>{{ $value->name }}</td>
                                <td>{{ $value->price }}</td>
                                <td>{{ $value->details }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                {!! $products->render() !!}
            </div>
        </div>
    </div>
</body>
</html>

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/ajax-pagi
Preview

It will help you...

#Laravel 8 #Laravel