Laravel 5.3 - Customize pagination templates example from scratch

https://www.itsolutionstuff.com/post/laravel-53-customize-pagination-templates-example-from-scratchexample.html

C:\xampp\htdocs\reset\routes\web.php

<?php
use App\Http\Controllers\HomeController;
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('/', [HomeController::class, 'tags'])->name('tags');
Route::get('/test', [HomeController::class, 'tags'])->name('tags');
// Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');

C:\xampp\htdocs\reset\app\Http\Controllers\HomeController.php

<?php
namespace App\Http\Controllers;
use DB;
class HomeController extends Controller {
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct() {
    // $this->middleware('auth');
  }
  /**
   * Show the application dashboard.
   *
   * @return \Illuminate\Contracts\Support\Renderable
   */
  public function index() {
    return view('home');
  }
  public function tags() {
    $tags = DB::table('tags')->paginate(7);
    return view('tags', compact('tags'));
  }
}

C:\xampp\htdocs\reset\resources\views\vendor\pagination\custom.blade.php

@if ($paginator->hasPages())
    <ul class="pager">
        {{-- Previous Page Link --}}
        @if ($paginator->onFirstPage())
            <li class="disabled"><span>← Previous</span></li>
        @else
            <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">← Previous</a></li>
        @endif
        {{-- Pagination Elements --}}
        @foreach ($elements as $element)
            {{-- "Three Dots" Separator --}}
            @if (is_string($element))
                <li class="disabled"><span>{{ $element }}</span></li>
            @endif
            {{-- Array Of Links --}}
            @if (is_array($element))
                @foreach ($element as $page => $url)
                    @if ($page == $paginator->currentPage())
                        <li class="active my-active"><span>{{ $page }}</span></li>
                    @else
                        <li><a href="{{ $url }}">{{ $page }}</a></li>
                    @endif
                @endforeach
            @endif
        @endforeach
        {{-- Next Page Link --}}
        @if ($paginator->hasMorePages())
            <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">Next →</a></li>
        @else
            <li class="disabled"><span>Next →</span></li>
        @endif
    </ul>
@endif

C:\xampp\htdocs\reset\resources\views\tags.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel custom pagination template</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style type="text/css">
    .my-active span{
      background-color: #5cb85c !important;
      color: white !important;
      border-color: #5cb85c !important;
    }
  </style>
</head>
<body>
<div class="container">
  <h1 class="text-primary">Laravel 5.3 - Customize pagination templates</h1>
  <table class="table table-bordered">
    <thead>
      <th>Id</th>
      <th>Name</th>
      <th>Creation Date</th>
      <th>Updated Date</th>
    </thead>
    <tbody>
      @foreach($tags as $key => $tag)
        <tr>
          <td>{{ ++$key }}</td>
          <td>{{ $tag->name }}</td>
          <td>{{ $tag->created_at }}</td>
          <td>{{ $tag->updated_at }}</td>
        </tr>
      @endforeach
    </tbody>
  </table>
</div>
{{ $tags->links('vendor.pagination.custom') }}
</body>
</html>

C:\xampp\htdocs\reset\database\migrations\2022_05_16_174656_create_tags_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTagsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('tags', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('tags');
  }
}

C:\xampp\htdocs\reset\database\seeders\DatabaseSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run() {
    // \App\Models\User::factory(100)->create();
    \App\Models\Tag::factory(100)->create();
  }
}

C:\xampp\htdocs\reset\database\factories\UserFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory {
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name'              => $this->faker->name(),
      'email'             => $this->faker->unique()->safeEmail(),
      'email_verified_at' => now(),
      'password'          => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
      'remember_token'    => Str::random(10),
    ];
  }
  /**
   * Indicate that the model's email address should be unverified.
   *
   * @return \Illuminate\Database\Eloquent\Factories\Factory
   */
  public function unverified() {
    return $this->state(function (array $attributes) {
      return [
        'email_verified_at' => null,
      ];
    });
  }
}

C:\xampp\htdocs\reset\database\factories\TagFactory.php

<?php
namespace Database\Factories;
use App\Models\Tag;
use Illuminate\Database\Eloquent\Factories\Factory;
class TagFactory extends Factory {
  protected $model = Tag::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name' => $this->faker->text(10),
    ];
  }
}

C:\xampp\htdocs\reset\app\Models\Tag.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
  use HasFactory;
}

Laravel 5.3 - Customize pagination templates example from scratch

By Hardik Savani October 10, 2016 Category : LaravelPauseUnmuteLoaded: 4.23%FullscreenVDO.AIToday, I am going to tell you how to building and apply new custom paginator view in Laravel 5.3. Laravel 5.3 added new features and update for easily implement your own manual pagination blade template.

By Default Laravel 5.3 provide us very simple bootstrap pagination view. But if you are not using bootstrap and you want to change then you can simply change OR if you want to add new bootstrap pagination layout then you can do it.

In bellow example you can see how to create custom blade layout and use them. This example from scratch so you can simply implement it in your project or laravel 5.3 application. So, you can also see bellow preview of example pagination.

Preview:

Laravel 5.3 added some new things on pagination view files. Laravel 5.3 give us to simply change on existing default pagination layout also so, you can run bellow command and it will create some files for pagination view.

Ok, so first run bellow command:

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

After bellow command run you will get new folder "pagination" on views files(resources/views/vendor). In pagination folder you will get following files by default:

1)default.blade.php

2)bootstrap-4.blade.php

3)simple-bootstrap-4.blade.php

4)simple-default.blade.php

You can also use bellow blade template for pagination and also change on this files.

Step 1: Create New Table with Data

In first step, we are going to create new our own custom layout file from scratch so first we have to create new one table will some records.

In this example i created new table "tags" and with some

dummy data as like bellow screen shot.

tags table

Step 2: Add New Route

Ok, after created table and dummy data, we have to add new route for example so add bellow new "tags" route in web.php file.

routes/web.php

Route::get('tags', 'HomeController@tags');

Read Also: Laravel 5 custom pagination view example

Step 3: Add Controller Method

Ok, now we have to add new controller method "tags()" in your HomeController, so if you haven't created HomeController then you can create by following command put bellow code:

command for create controller

php artisan make:controller HomeController

app/Http/Controllers/HomeController.php

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Requests;use DB;class HomeController extends Controller{    public function tags()    {    	$tags = DB::table('tags')->paginate(7);    	return view('tags',compact('tags'));    }}

Step 4: Create Blade File For Pagination

Ok, now we have to create new custom.blade.php file for our custom pagination template. In this file changed bootstrap class and also add new text for next and previous so it seems different layout for pagination layout.

so first i going to create blade file and put bellow code:

resources/views/vendor/pagination/custom.blade.php

@if ($paginator->hasPages())    <ul class="pager">        {{-- Previous Page Link --}}        @if ($paginator->onFirstPage())            <li class="disabled"><span>← Previous</span></li>        @else            <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">← Previous</a></li>        @endif        {{-- Pagination Elements --}}        @foreach ($elements as $element)            {{-- "Three Dots" Separator --}}            @if (is_string($element))                <li class="disabled"><span>{{ $element }}</span></li>            @endif            {{-- Array Of Links --}}            @if (is_array($element))                @foreach ($element as $page => $url)                    @if ($page == $paginator->currentPage())                        <li class="active my-active"><span>{{ $page }}</span></li>                    @else                        <li><a href="{{ $url }}">{{ $page }}</a></li>                    @endif                @endforeach            @endif        @endforeach        {{-- Next Page Link --}}        @if ($paginator->hasMorePages())            <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">Next →</a></li>        @else            <li class="disabled"><span>Next →</span></li>        @endif    </ul>@endif

Step 5: Create New Blade File

At last we have to create tags.blade.php file and we will use our custom pagination template. So let's create new page and put bellow code on it.

resources/views/tags.blade.php

Read Also: Laravel 5.3 new feature and update - $loop variable

<!DOCTYPE html><html><head>	<title>Laravel custom pagination template</title>	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">	<style type="text/css">		.my-active span{			background-color: #5cb85c !important;			color: white !important;			border-color: #5cb85c !important;		}	</style>	</head><body><div class="container">	<h1 class="text-primary">Laravel 5.3 - Customize pagination templates</h1>	<table class="table table-bordered">		<thead>			<th>Id</th>			<th>Name</th>			<th>Creation Date</th>			<th>Updated Date</th>		</thead>		<tbody>			@foreach($tags as $key => $tag)				<tr>					<td>{{ ++$key }}</td>					<td>{{ $tag->name }}</td>					<td>{{ $tag->created_at }}</td>					<td>{{ $tag->updated_at }}</td>				</tr>			@endforeach		</tbody>	</table></div>{{ $tags->links('vendor.pagination.custom') }}</body></html>

Ok, now we are ready to run this example, so you can check...

Maybe it can help you...

Last updated