In this tutorial, we will learn Laravel 8 Pagination Example
Step 1:
Add Route routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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('users', [UserController::class, 'index']);
Step 2:
Create Controller app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = User::paginate(5);
return view('users',compact('data'));
}
}
Step 3:
Create Blade File resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 CRUD Application - rathorji.in</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Laravel 8 Pagination Example - rathorji.in</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th width="300px;">Action</th>
</tr>
</thead>
<tbody>
@if(!empty($data) && $data->count())
@foreach($data as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="10">There are no data.</td>
</tr>
@endif
</tbody>
</table>
{!! $data->links() !!}
</div>
</body>
</html>
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();
}
}
Pagination with appends parameter
{!! $data->appends(['sort' => 'votes'])->links() !!}
Pagination with appends request all parameters
{!! $data->appends(Request::all())->links() !!}
May this example help you.