Tuesday, November 19, 2024
Google search engine
HomeLanguagesLaravel Pagination Customizations

Laravel Pagination Customizations

To learn about Customize Pagination, you want to understand the following points.

  • What is pagination
  • Types of pagination
  • What are the methods
  • Steps to write customize laravel  pagination

What is pagination?

Pagination is a navigation bar that helps users to move from one page to another page. Customize Pagination means styling the navigation bar of pagination. Laravel docs say the Bootstrap CSS is the default CSS to style pagination.

In other frameworks, pagination can be painful, but Laravel makes it easier. There is a single configuration option in the app/config/view.php

The pagination() method specifies which view should be used to create pagination links.

PHP




<?php
    
// app/Http/Controllers/HomeController.php
namespace App\Http\Controllers;
use App\Student;
use Illuminate\Http\Request;
class StudentController extends Controller {
    public function index() {
        
        // Show all of the users for the application.
        $students = Student::latest()->paginate(5);
        return view('students', compact('students'));
    }
}


Types of pagination: There are two ways of writing pagination methods 

  1. simplePaginate() Method
  2. paginate() Method

The difference between the methods is that the paginate() view will show a “range” of links based on the current page, while the simplePaginate() view displays only the Prev and Next buttons.

What Are the methods?

Some methods are available in laravel docs to define the properties of laravel pagination. There are important methods listed below. 

  • count(): Count the number of entries on the current page.
  • getCurrentPage(): Denote current page number.
  • getFirstItem(): Fetch first item in the results.
  • getOptions(): Get the paginator options.
  • getUrlRange($start, $end): Set a range of pagination URLs.
  • getlastPage(): Fetch last page available. (This method is not available while using simplePaginate).
  • nextPageUrl(): Fetch URL for the next page.
  • onFirstPage(): Determine if the paginator is on the first page.
  • perPage(): The number of items to be shown per page.
  • previousPageUrl(): Get the URL of the previous page.

Customize Pagination View: By default, the views rendered to display the pagination links are compatible with the Bootstrap CSS framework. The easiest way to customize the pagination views is by exporting them to resources/views/vendor directory using the vendor:publish command 

php artisan vendor:publish --tag=laravel-pagination 

This command will automatically create the folder /resources/views/vendor/pagination.

The bootstrap-4 blade.php file is within the corresponding default pagination view. You may edit this file to modify the pagination HTML. 

If you want to design a different pagination view as the default pagination view then you might be used paginator default view and default SimpleView method within your AppServiceProvider:

PHP




<?php
use Illuminate\Pagination\Paginator;
public function boot() {
    Paginator::defaultView('view-name');
    Paginator::defaultSimpleView('view-name');
}
?>


If you don’t want to use Bootstrap CSS then you create your own custom.blade.php file. 

Steps to write customize Laravel pagination: In this section, we introduce how pagination is added and customized. To customize laravel you will need to take the following steps:

  1. Make model
  2. Make Controller and view
  3. Fetch data from the database table
  4. Show data with pagination

Make model: To fetch data from the database table you want to create one model. Remember the model name is the same as the table name in the database that wants to display. You can use the following command to create a model 

php artisan make : model User;

Make Controller and view: Then in the second step, you need to create a Controller to create a connection between the model and the view page. You can use the below command to create a Controller 

php artisan make : controller StudentController;

PHP




<?php
#app/Http/Controllers/HomeController.php
namespace App\Http\Controllers;
use App\Student;
use Illuminate\Http\Request;
class StudentController extends Controller {
    public function index() {
        $students = Student::latest()->paginate(5);
        return view('students', compact('students'));
    }
}
?>


Fetch data from a database table: Then you want updates web.php in the route directory to add Controllers in the route 

PHP




<?php
    #routes/web.php
    // code
    Route::get('/', 'HomeController@index');
?>


Show data with pagination: First, we create custom.blade.php and then extends it into students view 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
      
<p>Default code has been loaded into the Editor.</p>
  
</body>
<!-- resources/views/vendor/pagination/custom.blade.php -->
  
@if ($paginator->hasPages())
<nav aria-label="Page navigation example">
    <ul class="pagination justify-content-center">
        @if ($paginator->onFirstPage())
        <li class="page-item disabled">
            <a class="page-link" href="#" 
               tabindex="-1">Previous</a>
        </li>
        @else
        <li class="page-item"><a class="page-link" 
            href="{{ $paginator->previousPageUrl() }}">
                  Previous</a>
          </li>
        @endif
  
        @foreach ($elements as $element)
        @if (is_string($element))
        <li class="page-item disabled">{{ $element }}</li>
        @endif
  
        @if (is_array($element))
        @foreach ($element as $page => $url)
        @if ($page == $paginator->currentPage())
        <li class="page-item active">
            <a class="page-link">{{ $page }}</a>
        </li>
        @else
        <li class="page-item">
            <a class="page-link" 
               href="{{ $url }}">{{ $page }}</a>
        </li>
        @endif
        @endforeach
        @endif
        @endforeach
  
        @if ($paginator->hasMorePages())
        <li class="page-item">
            <a class="page-link" 
               href="{{ $paginator->nextPageUrl() }}" 
               rel="next">Next</a>
        </li>
        @else
        <li class="page-item disabled">
            <a class="page-link" href="#">Next</a>
        </li>
        @endif
    </ul>
  </nav>
    @endif
  
</html>


Then later we create a view page to display data as a users list. It is blade.php file ex. student.blade.php

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>User list</title>
</head>
  
<body>
    <!-- resources/views/students.blade.php -->
    @extends('students.layout')
    @section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left text-center">
                <h2>Laravel 8 CRUD Operation 
                  Tutorial for Beginners</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" 
                   href="{{ route('students.create') }}">
                    Create Student</a>
            </div><br>
        </div>
    </div>
    @if ($message = Session::get('success'))
    <div class="alert alert-success"> <span>
            {{ $message }}</span>
    </div> @endif
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Age</th>
            <th>Action</th>
        </tr> @foreach ($students as $student)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $student->firstname }}</td>
            <td>{{ $student->lastname }}</td>
            <td>{{ $student->age }}</td>
            <td>
                <form action=
"{{ route('students.destroy',$student->id) }}" method="POST">
                    <a class="btn btn-info" href=
"{{ route('students.show',$student->id) }}">Show</a>
                    <a class="btn btn-primary" href=
"{{ route('students.edit',$student->id) }}">Edit</a>
                    @csrf @method('DELETE')
                    <button type="submit" onclick=
"return confirm('Do you really want to delete student!')"
                        class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr> @endforeach
    </table>
    {{ $students->links('vendor.pagination.custom') }}
    @endsection
</body>
  
</html>


Output:

Laravel customize Pagination 

RELATED ARTICLES

Most Popular

Recent Comments