Pagination Laravel 9 – Tutorial pagination Laravel 9 dengan Bootstrap 5 dan database MySQL. Kasus kali ini adalah mengolah data pelanggan (Customer).
1. Membuat Project Laravel
Pastikan Anda sudah menginstall composer, kemudian jalankan perintah berikut di command prompt.
composer create-project laravel/laravel laravel-pagination
2. Mengatur Database MySQL
Buat database dengan nama laravel_pagination di http://localhost/phpmyadmin jika Anda menginstall XAMPP untuk server MySQL.
Sesuaikan pengaturan koneksi mysql di project laravel pada file .env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_pagination DB_USERNAME=root DB_PASSWORD=
Sesuaikan DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, dan DB_PASSWORD sesuai server MySQL.
3. Membuat Migration Customer
Laravel 9 sudah menyediakan migration untuk users, password_resets, failed_jobs, dan personal_access_tokens yang ada di direktori database/migrations. Anda bisa menghapus file tersebut dan membuat migration baru dengan perintah berikut.
php artisan make:migration create_customers_table
Kemudian sesuaikan field pada migration sebagai berikut.
<?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('customers', function (Blueprint $table) {
$table->id('customer_id');
$table->string('customer_name');
$table->string('contact_name');
$table->string('address');
$table->string('city');
$table->string('postal_code');
$table->string('country');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customers');
}
};
Lakukan migration dengan mengetikan perintah berikut.
php artisan migrate
Setelah berhasil menjalankan perintah migrate, maka di database akan ada tabel customers.
4. Membuat Model Customer (Eloquent)
Buat model Customer menggunakan perintah berikut.
php artisan make:model Customer
Hasil dari model yang dibuat ada di app/models/Customer.php sebagai berikut.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use HasFactory;
}
5. Membuat Factory + Faker
Factory dan Faker berfungsi untuk membuat data dummy sebagai percobaan. Jika Anda sudah punya data bisa diimport atau diinput lewat phpmyadmin dan lewati langkah ini, langsung menuju ke langkah 7 . Buat Factory untuk model Customer dengan nama CustomerFactory dengan perintah berikut.
php artisan make:factory CustomerFactory
Pastikan nama factory sesuai dengnan nama model, diikuti dengan akhiran Factory. Sesuaikan data dummy di database/factories/CustomerFactory.php sebagai berikut.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
*/
class CustomerFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'customer_name' => $this->faker->name(),
'contact_name' => $this->faker->lastName(),
'address' => $this->faker->address(),
'city' => $this->faker->city(),
'postal_code' => $this->faker->postcode(),
'country' => $this->faker->country(),
];
}
}
6. Membuat Seeder
Seeder berfungsi untuk membangkitkan data sesuai data dummy yang sudah diatur di CustomerFactory. Pada kasus ini, akan dibuat 500 data dummy. Sesuaikan file database/seeders/DatabaseSeeder.php sebagai berikut.
<?php
namespace Database\Seeders;
use App\Models\Customer;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
Customer::factory(500)->create();
}
}
Jalankan DatabaseSeeder menggunakan perintah berikut.
php artisan db:seed
Maka pada tabel customer akan ada data dummy sebanyak 500 data.
7. Membuat Controller Customer
Gunakan perintah berikut untuk membuat controller.
php artisan make:controller CustomerController
Sesuaikan app/controllers/CustomerController.php sebagai berikut.
<?php
namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
class CustomerController extends Controller
{
public function index(Request $request)
{
$data['q'] = $request->get('q');
$data['customers'] = Customer::where('customer_name', 'like', '%' . $data['q'] . '%')->paginate(10)->withQueryString();
return view('customer.index', $data);
}
}
Perintah $request->get('q') berfungsi untuk mengambil input pencarian dari url.
Perintah where('customer_name', 'like', '%' . $data['q'] . '%') berfungsi sebagai query mengandung kata $data['q'].
Perintah paginate(10) berfungsi membuat halaman dimana terdiri dari 10 item setiap halaman.
Perintah withQueryString() berfungsi agar query string di url (misal: q atau pencarian) tetap ditampilkan di setiap halaman.
8. Menambahkan Route Customer
Tambahkan route untuk crud user di routes/web.php bertipe resource seperti berikut.
<?php
use App\Http\Controllers\CustomerController;
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('/', function () {
return view('welcome');
});
Route::get('customer', [CustomerController::class, 'index']);
9. Membuat View
Buat view untuk menampilkan data customer di direktori resources/views/customer/index.blade.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Pagination Laravel</title>
</head>
<body>
<div class="container">
<h1>Customers</h1>
<div class="card">
<div class="card-header">
<form class="row row-cols-lg-auto g-1">
<div class="col">
<input class="form-control" type="text" name="q" value="{{ $q }}" placeholder="Search here..." />
</div>
<div class="col">
<button class="btn btn-success">Search</button>
</div>
</form>
</div>
<div class="card-body p-0">
<table class="table table-bordered table-striped table-hover m-0">
<thead>
<tr>
<th>#</th>
<th>Customer Name</th>
<th>Contact Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<?php
$i = $customers->firstItem();
?>
@foreach($customers as $customer)
<tr>
<td>{{ $i++ }}</td>
<td>{{ $customer->customer_name }}</td>
<td>{{ $customer->contact_name }}</td>
<td>{{ $customer->address }}</td>
<td>{{ $customer->city }}</td>
<td>{{ $customer->postal_code }}</td>
<td>{{ $customer->country }}</td>
</tr>
@endforeach
</table>
</div>
@if($customers->hasPages())
<div class="card-footer">
{{ $customers->links() }}
</div>
@endif
</div>
</div>
</body>
</html>10. Mengatur Template Pagination
Atur agar template pagination sesuai dengan bootstrap 5 di app/providers/AppServiceProvider.php sebagai berikut.
<?php
namespace App\Providers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Paginator::useBootstrapFive();
}
}
11. Menjalankan Project
Silahkan gunakan perintah berikut untuk mengaktifkan server laravel.
php artisan serve
Ketikkan alamat sesuai server diikuti dengan /customer di browser (http://127.0.0.1:8000/customer). Hasilnya seperti berikut.


Itulah tutorial membuat Pagination Laravel 9. Jika ada yang ditanyakan, silahkan berkomentar.