In this tutorial we learn how to create pagination in Laravel.
Laravel has built-in functions for the pagination of data. When we are using Laravel, we do not need to write a lot of code, there are built-in functions for pagination in Laravel.
#Create Controller
#Create Funcrion in AppServiceProvider file
#Create view file
#Create route
Example 1
Controller – CustomerController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Customer; class CustomerController extends Controller { public function customers() { $customers = Customer::paginate(2); return view('index', compact('customers')); } }
Add below code in AppServiceProvider.php file
public function boot() { Paginator::useBootstrap(); }
View File – 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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap4.min.css"> <title>Laravel Order By Relation</title> </head> <body> <div class="container mt-5"> <div class="text-center"> <h1>Laravel Render Html In Controller</h1> </div> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <th>Id</th> <th>Name</th> <th>Email</th> <th>Address</th> <th>City</th> <th>State</th> </thead> <tbody> @foreach($customers as $key => $customer) <tr> <td>{{++$key}}</td> <td>{{$customer->name}}</td> <td>{{$customer->email}}</td> <td>{{$customer->address}}</td> <td>{{$customer->city}}</td> <td>{{$customer->state}}</td> </tr> @endforeach </tbody> </table> {!! $customers->links() !!} </div> </body> </html>
Route – web.php file
Route::get('/', function () { return view('index'); }); Route::get('/', 'CustomerController@customers')->name('index');
Output
Example 2
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Customer; class CustomerController extends Controller { public function customers() { $customers = Customer::simplePaginate(2); return view('index', compact('customers')); } }