Laravel Ajax Pagination Without Page Reload - WebJourney

Laravel Ajax Pagination Without Page Reload - WebJourney

Laravel default pagination is very easy and simple process. For making pagination laravel provides two methods paginate() and simplePaginate(), using these methods we can do pagination very easily. But we need something more special that means today will build a pagination system without any page loading with the help of ajax. There are several steps bellow to complete this process.

 

1. Setup a project

2. Database create and connect

3. Model and migration create

4. Required routes create

5. Controller create

6. Create blade file

7. Run application

 

 

 

Step 1: Setup a project

 

You can use your any existing project or just install a new project to make pagination system. We will use both composer and laravel installer to setup a new project. Let's create a new project laravel-ajax-pagination via composer

//using composer
composer create-project laravel/laravel laravel-ajax-pagination

//using laravel installer 
laravel new laravel-ajax-pagination

 

 

 

Step 2: Database create and connect

 

Once the project installation is successfull we will creata a database laravel_ajax_pagination and connect the database to our project. Now open .env file from your app in an editor and put the database credentials as bellow.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_pagination
DB_USERNAME=root
DB_PASSWORD=

 

 

 

Step 3: Model and migration create

 

Create a model with migration with the bellow command. A model name can be anything but a relavent name is always good for understending the workflow.  So let's create a model LaravelAjaxPagination and migration file together using the artisan command.

php artisan make:model LaravelAjaxPagination -m

 

See model LaravelAjaxPagination is created inside App\Models folder and migration file also created inside database\migration. First open migration file and add required field for laravel_ajax_paginations table.

laravel_ajax_paginations_table .php

<?php

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

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

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

 

Now run migrate command for create a table in database

php artisan migrate

Ok, table is created successfully now insert dummy data into the table so that you can check your application. I'm inserting few data manualy for test purpose. You can insert data by creating seeder, factory , upload a csv file or manually.

 

 

Step 4: Required routes create

 

We have to create required routes for pagination in web.php file

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxPaginateController;


Route::get('/',[AjaxPaginateController::class,'show_data'])->name('show.data');
Route::get('/ajax-paginate',[AjaxPaginateController::class,'ajax_paginate'])->name('ajax.paginate');

 

 

 

Step 5: Controller create

 

In this step we will create a controller AjaxPaginateController so that we can return our view file and create pagnaation logic.

php artisan make:controller AjaxPaginateController

AjaxPaginateController.php

<?php

namespace App\Http\Controllers;

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

class AjaxPaginateController extends Controller
{
    public function show_data()
    {
        $records = LaravelAjaxPagination::latest()->paginate(5);
        return view('welcome',compact('records'));
    }

    public function ajax_paginate(Request $request){
        $records = LaravelAjaxPagination::latest()->paginate(5);
        return view('paginate_records',compact('records'))->render();
    }
}

 

 

 

Step 6: Create blade file

 

Now we need to create a blade file  paginate_records.blade.php inside resources\views directory.

After create the file we will paste the bellow code in welcome.blade.php file.

resources\views\welcome.blade.php

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
     <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Laravel 9 Ajax Pagination-WebJourney</title>
  </head>
  <body>
      <div class="container">
          <div class="row">
              <div class="col-md-2"></div>
              <div class="col-md-8">
                  <h2 class="my-5 text-center">Laravel 9 Ajax Pagination Without Page reload</h2>
                  <div class="table-data">
                    <table class="table table-bordered">
                        <thead>
                          <tr>
                            <th scope="col">#</th>
                            <th scope="col">Name</th>
                            <th scope="col">Email</th>
                          </tr>
                        </thead>
                        <tbody>
                            @foreach($records as $key=>$rec)
                              <tr>
                                <th>{{ $key+1 }}</th>
                                <td>{{ $rec->name }}</td>
                                <td>{{ $rec->email }}</td>
                              </tr>
                            @endforeach
                        </tbody>
                    </table>
                    {!! $records->links() !!}
                </div>
            </div>
        </div>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<script type="text/javascript">
     //pagination 
    $(document).on('click','.pagination a', function(e){
      e.preventDefault();
      let page = $(this).attr('href').split('page=')[1]
      record(page)
    })

    function record(page){
        $.ajax({
            url:"/ajax-paginate?page="+page,
            success:function(res){
                $('.table-data').html(res);
            }
        })
    }

</script> 

</body>
</html>

 

resources\views\paginate_records.blade.php

<table class="table table-bordered">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Email</th>
      </tr>
    </thead>
    <tbody>
        @foreach($records as $key=>$rec)
          <tr>
            <th>{{ $key+1 }}</th>
            <td>{{ $rec->name }}</td>
            <td>{{ $rec->email }}</td>
          </tr>
        @endforeach
    </tbody>
</table>
{!! $records->links() !!}

 

Note: don't forget to modify your boot method in AppServiceProvider and import Paginator class show in bellow.

App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

 

 

 

Step 7: Run application

 

Now run artisan development server and  test your application. Hope that helps yuo a lot.

php artisan serve

 

 

 

 

If you like what you are reading, please think about buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support 

Tags

  • Share This: