Hello Dev.
On this article, i'm able to share a way to create simple pagination within the Laravel 8 application. we are able to learn how to assemble easy pagination in laravel 8 utility from scratch. we will setting in a laravel app, creating model and migrations, creating a controller and connecting controller to routes, and fetch facts from the database and bind with pagination() method to show results in smaller sizes using paginate() and links() function.
We can also focus on how to set up a custom path or parameter with laravel pagination and convert pagination outcomes into JSON.
Integrating Pagination in Laravel is very easy due to query builder and Eloquent ORM. It gives a handy and creative way to display database results in smaller portions. The pagination works well with the Bootstrap CSS framework.
So let's start the lesson...
First of all we want to get clean and new Laravel application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it:
composer create-project laravel/laravel --prefer-dist laravel-pagination
go inside the project directory.
cd laravel-pagination
Second step, we configure database like database name, username, password etc application of laravel. let's open .env file and fill complete details equal as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(laravel_db)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Pagination is used to show the massive amount of records in chunks, so we want to create a Model that takes care of business logic of our Laravel application. A model refers back to the logical structure of the data table in our database.
php artisan make:model Employee -m
Open database/migrations/timestamp_create_employees_table.php file and add the schema.
timestamp_create_employees_table.php
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->string('dob');
});
}
Include the following code in the app/Models/Employee.php file to register the schema in the $fillable array.
Employee.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = [
'firstname',
'lastname',
'email',
'dob',
];
}
Execute the following command from the command-line tool for database migration.
php artisan migrate
To display pagination in Laravel, we need to create some fake data so that we can divide that data in small chunks. So, to generate false data, we can use the built-in Laravel package, Faker.
Open the database/seeds/DatabaseSeeder.php file and place the following code.
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
foreach (range(1,500) as $index) {
DB::table('employees')->insert([
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'email' => $faker->email,
'dob' => $faker->date($format = 'D-m-y', $max = '2010',$min = '1980')
]);
}
}
}
To generate faux random data inside the database declare DB and Faker services at the top, Run a foreach loop and define the range of the data that you have to generate within the database. define the table name and schema inside the table insert function.
Execute the given command to generate the data.
php artisan db:seed
Now, you can take a look at your employees table in the database with as a minimum 500 new data that you could use for Laravel pagination demo.
Execute the command to create an employee controller.
php artisan make:controller EmployeeController
Add the following code to app/Http/EmployeeController.php.
EmployeeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
public function getData(){
$employeeData = Employee::all();
return view('home', compact('employeeData'));
}
}
Add the following code to routes/web.php to define the route and bind it to the controller.
web.php
use App\Http\Controllers\ EmployeeController;
Route::get('/', [EmployeeController::class, 'getData']);
Creating a blade file resources/views/home.blade.php, within which you should insert the following code to prepare Laravel for rendering employee records using Bootstrap Table components.
home.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Laravel Pagination Demo - meaningarticles.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<table class="table table-bordered mb-5">
<thead>
<tr class="table-success">
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
<th scope="col">Email</th>
<th scope="col">DOB</th>
</tr>
</thead>
<tbody>
@foreach($employees as $data)
<tr>
<th scope="row">{{ $data->id }}</th>
<td>{{ $data->firstname }}</td>
<td>{{ $data->lastname }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->dob }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>
In Laravel, pagination allows you to display extensive data in smaller segments. Laravel pagination is very easy to use, as it is integrated with the query builder and Eloquent ORM. Laravel pagination automatically covers limit and offset.
In laravel, pagination can be implemented by adding the laravel paginate function in the getData() method of the EmployeeController class. Remove all() and use paginate(), where the number defines the number of results the user will be shown.
app/http/controllers/EmployeeController.php
class EmployeeController extends Controller {
public function getData(){
$employees = Employee::paginate(8);
return view('home', compact('employees'));
}
}
This code would need to be added to the home.blade.php file below the table component. Since Laravel pagination works well with Bootstrap 4, we don't need to worry about the pagination UI.
<div class="d-flex justify-content-center">
{!! $employees->links() !!}
</div>
Here is the final home.blade.php file.
home.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Laravel Pagination Demo - meaningarticles.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<table class="table table-bordered mb-5">
<thead>
<tr class="table-success">
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
<th scope="col">Email</th>
<th scope="col">DOB</th>
</tr>
</thead>
<tbody>
@foreach($employees as $data)
<tr>
<th scope="row">{{ $data->id }}</th>
<td>{{ $data->firstname }}</td>
<td>{{ $data->lastname }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->dob }}</td>
</tr>
@endforeach
</tbody>
</table>
{{-- Pagination --}}
<div class="d-flex justify-content-center">
{!! $employees->links() !!}
</div>
</div>
</body>
</html>
We've got created a simple pagination which shows a couple of pages of outcomes and creates a url something like this. essentially, it appends a ?page=3.
We can simply add the additional parameter to the pagination url by simply the usage of the subsequent code.
{!! $employees->appends(['sort' => 'department'])->links() !!}
Moreover, you need to import and define useBootstrap() in the boot function inside the app/Providers/AppServiceProvider.php.
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();
}
}
The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable Interface contract and expose the toJson method. It is straightforward to convert your pagination effects into JSON. you could also convert a paginator example to JSON by using returning it from a route or controller action.
Open routes/web.php file and place the following route with paginate function.
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| right here is in which you may register web routes to your application.
| those routes are loaded with the aid of the RouteServiceProvider inside a
| group which contains the "web" middleware group. Now create some thing tremendous!
|
*/
Route::get('/', [EmployeeController::class, 'getData']);
Route::get('/convert-to-json', function () {
return App\Employee::paginate(5);
});
you could get the pagination JSON data on URL:
http://127.0.0.1:8000/convert-to-json
{
"current_page":1,
"data":[
{
"id":1,
"firstname":"Hardy",
"lastname":"Kuhlman",
"email":"[email protected]",
"dob":"Thu-01-70"
},
{
"id":2,
"firstname":"Missouri",
"lastname":"Gaylord",
"email":"[email protected]",
"dob":"Thu-01-70"
},
{
"id":3,
"firstname":"Kaela",
"lastname":"O'Hara",
"email":"[email protected]",
"dob":"Thu-01-70"
},
{
"id":4,
"firstname":"George",
"lastname":"O'Kon",
"email":"[email protected]",
"dob":"Thu-01-70"
},
{
"id":5,
"firstname":"Chaim",
"lastname":"Jerde",
"email":"[email protected]",
"dob":"Thu-01-70"
}
],
"first_page_url":"http:\/\/127.0.0.1:8000\/home?page=1",
"from":1,
"last_page":100,
"last_page_url":"http:\/\/127.0.0.1:8000\/home?page=100",
"next_page_url":"http:\/\/127.0.0.1:8000\/home?page=2",
"path":"http:\/\/127.0.0.1:8000\/home",
"per_page":5,
"prev_page_url":null,
"to":5,
"total":500
}
Execute the following command to begin the Laravel pagination demo project.
php artisan serve
You check the app on http://127.0.0.1:8000
I hope it assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.
Happy Coding.....