Displaying a large number of records in a single table is not a big issue. But managing these records properly in a single table can be an issue. Actually, I am talking about the number of rows that will be displayed in a single table. This will become cumbersome of the data within a single web page. Also, it will cover the entire page for those rows of the data. That’s why we’d use the Laravel pagination. Pagination allows us to divide a large number of data in chunks. It makes easy access to handling these kinds of issues. I have already shown you the use of data tables in Laravel 6. Datatable provides the functionality of live searching, sorting, pagination, etc. Through this post, I will be implementing the Laravel 6 pagination example.
Prerequisites
It is necessary to have the following requirements in your system. So that you can create a new fresh project in Laravel 6.
- PHP version >=7.3.9
- MySQL (version > 5)
- Apache/Nginx Server
Once, you are ready for creating a new project with your system, let’s go ahead.
Create a New Laravel 6 Project For Pagination
In this post, we’ll start with a new fresh project. So, for creating a new project, just enter the below command in the terminal or command prompt.
composer create-project --prefer-dist laravel/laravel laravel6-pagination
Once your project setup is ready, let’s go ahead with the database creation and configuration steps.
How to Integrate Laravel 6 Application with Firebase
Create a New Database in MySQL
If you are using phpMyAdmin then create a new database with any name. If you are using the MySQL command line then enter the below command there.
CREATE DATABASE laravel6_pagination;
It will create a new database. In the next step, we’ll have to connect our project with this database.
Connect Laravel 6 Project with MySQL Database
For connecting the Laravel 6 project just open the .env file. Then replace the following code with yours.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_pagination
DB_USERNAME=root
DB_PASSWORD=root
That’s it for the database connectivity. Now, we’ll move on to the migration.
How to Send Email in Laravel 6 Via Gmail Using SMTP
Create Migration in Laravel 6 For Pagination
In this project, we don’t need to create any migration and Model. Actually, the Laravel project adds a default Model and migration for the User. So, as far we no need any model and migration yet.
You can find the migration file inside the database/migrations. Here, this is the default schema for the users table. Here, you can change the schema if you want. But, currently, we no need to change anything here. Just leave it as default.
// create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Laravel 6 Login and Registration with Authentication
Migrate Table Schema
For creating the above table you will need to migrate the table. In the migration process, the table will be created with the specified schema. For migrating the table, just enter the below command.
php artisan migrate
After the successful migration of the table, you can check the list of tables in the database.
Once, the above steps have done, move to the next step. In the next step, we’ll add some dummy records in the users table.
Add Dummy Records For Pagination
Laravel 6 provides a predefined function for adding dummy records into the database tables. By using this approach you can add dummy records as much you can. So, here, I am going to use the Tinker factory method.
php artisan tinker
factory(App\User::class, 200)->create();
Enter the above command in the terminal. It will insert the 200 dummy records in the users table.
You can check into the database table. The users table has 200 records inserted. Now, we can fetch these records in the table for implementing the pagination.
For displaying the records I am going to create a Controller file. So, that I can write the eloquent for the Laravel pagination example.
Laravel 6 Custom Login and Registration with Session
Create Controller in Laravel
For implementing Laravel pagination we will need to write a function. So, for this, we will need a controller where we will call the Model.
php artisan make:controller UserController
The above command will create a controller with the name UserController.
After creating the controller just enter the below code there.
// UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index() {
$users = User::all();
return view('user', compact('users'));
}
}
In the above code, I have fetched all the records from the users table. In this case, I haven’t implemented the pagination.
Create Route
For the above controller function, we’ll need a route that will call the above function. So, in the routes/web.php add the below route.
Route::get('users', 'UserController@index');
Create a View For Displaying Records
For displaying the records, we’ll need to create a view in which all the records will be fetched. So, in the resources/views create a blade file. In my case, I have created a file named user.blade.php.
Now, add the below snippet that will display the records from the controller.
<!-- user.blade.php -->
<!doctype html>
<html lang="en">
<head>
<title>Pagination Example in Larvel 6</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-2 mb-3">
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
<h4 class="text-center mb-5"> Pagination Example in Laravel 6 </h4>
<table class="table table-striped mt-2">
<thead>
<th> ID </th>
<th> Name </th>
<th> Email </th>
<th> Created at </th>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td> {{ $user->id }} </td>
<td> {{ $user->name }} </td>
<td> {{ $user->email }} </td>
<td> {{ $user->created_at }} </td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
Save and run the application using the artisan command.
php artisan serve
When your application will start, just enter the below URL in the browser.
http://localhost:8000/users
It will come up with the below result with the list of entire records from the users table.
In the above result, I didn’t apply the pagination. Also, I have fetched all the records from eloquent. That’s why It is showing all records.
Laravel 6 REST API For ToDo Application with Passport Auth
Implement Laravel Pagination
When you want to apply the pagination, then replace the below code with the above controller function. Instead of all just write the number of records that you want to display in the pagination.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index() {
$users = User::paginate(10);
return view('user', compact('users'));
}
}
When you run your application again, it will display only 10 records in the table.
But, have you noticed here, the pagination hasn’t applied on the table. Yes, actually, I have written the code for displaying the number of records in the table. But haven’t implemented the pagination.
So, for this, we’ll have to write a single line of code in the view. From the controller to view, I have passed the users variable. So in the HTML area after the closing of the table tag, just put the single line of code.
{{ $users->links() }}
After placing the above code, the view will become.
<!doctype html>
<html lang="en">
<head>
<title>Pagination Example in Larvel 6</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-2 mb-3">
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
<h4 class="text-center mb-5"> Pagination Example in Laravel 6 </h4>
<table class="table table-striped mt-2">
<thead>
<th> ID </th>
<th> Name </th>
<th> Email </th>
<th> Created at </th>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td> {{ $user->id }} </td>
<td> {{ $user->name }} </td>
<td> {{ $user->email }} </td>
<td> {{ $user->created_at }} </td>
</tr>
@endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
Now, save and re-run your application. As a result, you can see the pagination has been applied to the HTML table.
Pagination in JSON Data
Similarly, we can achieve pagination with the RESTful APIs where we need the JSON data. I am going to show you how you can create this.
In the UserController.php just add the below function.
// Return JSON data with pagination
public function paginationToJson() {
$users = User::paginate(10);
return response()->json($users);
}
Now, for the above function make a route. Add this route in the same route (web.php) file. This is just for a demonstration purpose. That’s why I am adding this route in the same route file (web.php) file. Otherwise, for APIs, Laravel provides a separate file for routes. That is api.php.
Route::get('users-json', 'UserController@paginationToJson');
Once, you have added the above route. Let’s open the POSTMAN and hit the below URL.
http://localhost:8000/users-json
For the above API, use the request type to GET.
Now, you have the result of data in the JSON with the pagination.
How to Resize Image in Laravel 6 Before Upload
You will have the URL for the next page, the previous page, the total number of records, start page number and end page number, per page data and so on.
Conclusion
Conclusively, we have achieved the pagination for the array data. Also, for the JSON data. I wish this will help you in creating your real projects. The good thing in the Laravel is that you can create pagination with the JSON data too. So, using this approach, you can create APIs and projects.
Leave a Reply