😅Phân trang trong Laravel kết hợp sử dụng Ajax, pagination full (ok)

Phân trang trong Laravel kết hợp sử dụng Ajax

C:\xampp\htdocs\datvietcoconut\database\factories\ProductFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition()
  {
    return [
      "name" => $this->faker->name(),
      "status" => $this->faker->randomElement(['Pending', 'Wait', 'Active'])
    ];
  }
}

C:\xampp\htdocs\datvietcoconut\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| 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('/', [HomeController::class,'index']);
Route::get('fetch-products',  [HomeController::class,'fetch_products']);

C:\xampp\htdocs\datvietcoconut\app\Http\Controllers\HomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class HomeController extends Controller
{
  function index()
  {
    $products = Product::paginate(5);
    return view('home', compact('products'));
  }
  function fetch_products(Request $request)
  {
    if ($request->ajax()) {
      $products = Product::paginate(5);
      return view('data', compact('products'));
    }
  }
}

C:\xampp\htdocs\datvietcoconut\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()
  {
    if ($this->app->environment() !== 'production') {
      $this->app->register(\Sven\ArtisanView\ServiceProvider::class);
    }
  }
  /**
   * Bootstrap any application services.
   *
   * @return void
   */
  public function boot()
  {
    Paginator::useBootstrap();
  }
}

C:\xampp\htdocs\datvietcoconut\resources\views\home.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Pagination using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
    .box {
      width: 600px;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <br />
  <div class="container">
    <h3 align="center">Laravel Pagination using Ajax</h3><br />
    <div id="table_data">
      <div class="table-responsive">
        <table class="table table-striped table-bordered">
          <tr>
            <th width="5%">ID</th>
            <th width="38%">Title</th>
            <th width="57%">Description</th>
          </tr>
          @include('data')
      </div>
    </div>
  </div>
</body>
</html>
<script>
  $(document).ready(function() {
        $(document).on('click', '.pagination a', function(event) {
            event.preventDefault();
            var page = $(this).attr('href').split('page=')[1];
            fetch_products(page);
        });
        function fetch_products(page) {
          $.ajax({
            url: "/fetch-products?page=" + page,
            success: function(data) {
              $('#table_data').html(data);
            }
          });
        }
    });
</script>

C:\xampp\htdocs\datvietcoconut\resources\views\data.blade.php

<div class="table-responsive">
  <table class="table table-striped table-bordered">
    <tr>
      <th width="5%">ID</th>
      <th width="38%">Title</th>
      <th width="57%">Description</th>
    </tr>
    @foreach($products as $product)
    <tr>
      <td>{{ $product->id }}</td>
      <td>{{ $product->name }}</td>
      <td>{{ $product->status }}</td>
    </tr>
    @endforeach
  </table>
  {!! $products->links() !!}
</div>

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_083000_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->enum('status', ['Pending', 'Wait', 'Active'])->default('Pending');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('products');
  }
}

C:\xampp\htdocs\datvietcoconut\database\factories\ProductFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition()
  {
    return [
      "name" => $this->faker->name(),
      "status" => $this->faker->randomElement(['Pending', 'Wait', 'Active'])
    ];
  }
}

C:\xampp\htdocs\datvietcoconut\database\seeders\DatabaseSeeder.php

use Illuminate\Database\Seeder;
// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    $faker = Faker::create();
    foreach (range(1, 500) as $index) {
      DB::table('employees')->insert([
        'firstname' => $faker->firstname,
        'lastname' => $faker->lastname,
        'email' => $faker->email,
        'dob' => $faker->date($format = 'D-m-y', $max = '2010', $min = '1980')
      ]);
    }
  }
}

Ví dụ 2:

C:\xampp\htdocs\datvietcoconut\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\ArticlesController;
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| 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('/', [HomeController::class,'get_home']);

C:\xampp\htdocs\datvietcoconut\app\Http\Controllers\HomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class HomeController extends Controller
{
  /**
   * Show the application dashboard.
   *
   * @return \Illuminate\Contracts\Support\Renderable
   */
  public function get_home(Request $request)
  {
    if ($request->ajax() || 'null') {
      $products = Product::paginate(10);
      return view('home', compact('products'));
    }
  }
}

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_083000_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->enum('status', ['Pending', 'Wait', 'Active'])->default('Pending');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('products');
  }
}

C:\xampp\htdocs\datvietcoconut\database\factories\ProductFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition()
  {
    return [
      "name" => $this->faker->name(),
      "status" => $this->faker->randomElement(['Pending', 'Wait', 'Active'])
    ];
  }
}

C:\xampp\htdocs\datvietcoconut\database\seeders\DatabaseSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Product;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    Product::factory(30)->create();
  }
}

Last updated