Laravel

Laravel Pagination Example.

The benefit of using any web application framework is that you don’t have to worry about the common tasks like input handling, form validation and the like, as the framework already provides wrappers for those features.

In other frameworks, pagination can be very painful. Laravel’s paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database results out of the box.The HTML generated by the paginator is compatible with the Bootstrap CSS framework.

Paginating Query Builder Results.

The simplest way to implement pagination in Laravel by using paginate method on the query builder or Eloquent ORM.

Features Of Paginate Method.

1The paginate method automatically set the proper limit and offset based on the current page being viewed by the user.
2.The current page is automatically highlighted based on page query string .
3.Total number of pages is automatically created.

Install Laravel App.

Create Laravel app by using below command.

composer create-project laravel/laravel --prefer-dist pagination_example

Configure Database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pagination_laravel
DB_USERNAME=root
DB_PASSWORD=

Create Model.

php artisan make:model Product

For sample data I have used classic models database. Download classicmodels database. Download this database from here . https://www.mysqltutorial.org/mysql-sample-database.aspx/

Create Controller.
php artisan make:controller ProductController.

Add below code in productController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    
    public function pagination(){
        $datas = Product::paginate(10);
        return view('paginate', ['datas' => $datas]);    
    }
}
Create Route
Route::get('pagination', 'ProductController@pagination');
Create View
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Laravel Pagination Example</title>  
</head>
<body>
<div class="container">
  <center><h3><u>Laravel Pagination Example</h3></u></center><br>  
 <table class="table table-bordered table-striped">  
<thead>  
<tr bgcolor="silver">  
<th>Id</th>
<th>Name</th>
<th>Product Line</th>
 <th>Product Vendor</th>
</tr>  
<thead>  
<tbody>  
@foreach ($datas as $index=>$data)
             <tr>
                     <td>{{++$index }}</td>
                    <td>{{ $data->name }}</td>
                    <td> {{ $data ->productLine }}</td>
                    <td>{{ $data->productVendor}}</td>
            </tr>
 @endforeach
</tbody>  
</table>  
 <p>{{ $datas->links() }}</p>
</div>
</body>
</html>

Related Articles

Leave a Reply

Back to top button