Laravel Pagination

Pagination is used to display many records at once by dividing the data into multiple pages to make it readable. Using pagination in Laravel is very simple because this feature is integrated with Eloquent ORM and a query builder. The limit and offset of the paginations are calculated automatically in Laravel. The paginate() and link() methods are used to implement pagination in Laravel. This tutorial shows you how to apply pagination in Laravel projects.

Prerequisites

Before starting this tutorial, you must complete the following tasks that are not covered in this tutorial.

A. Install a new Laravel project

B. Make the database connection

Create a Table Structure Using Migration

Here, the students table will be created by using migration to apply the pagination. Run the following command to create the migration file for the students table. If the command executes successfully, then it will create a migration file under the /database/migration folder.

$ php artisan make:migration create_students_table –create=students

Go to the folder and open the migration file. Modify the up() method with the following code to define the structure for the students table. The table will contain 7 fields. The id field will be the primary key and auto-increment field. The std_id, std_name, std_email, and std_mobile fields will contain string data. The last two fields will store the insertion and update the time of the record.

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('std_id');
        $table->string('std_name');
        $table->string('std_email')->unique();
        $table->string('std_mobile');
        $table->timestamps();
    });
}

Run the following command to create the table in the database.

$ php artisan migrate

If the table is created successfully, then you will get the following table structure.

Create Model

Run the following command from the terminal to create a model named Student for the students table. This will create a Student.php under the app folder.

$ php artisan make:model Student

Open the Student.php model and modify the file with the following code. Here, $fillable is declared to define which fields of the students table are mandatory. So, when the data is inserted, the std_id, std_name, std_email, and std_mobile fields cannot be kept empty.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'std_id',
        'std_name',
        'std_email',
        'std_mobile',
    ];
}

Generate Fake Data

A large number of records will be required to store in the students table to show the task of pagination properly. Here, the Faker service is used in the DatabaseSeeder class to quickly insert a large number of fake records in the students table for testing purposes. Open the DatabaseSeeder.php file from the location /database/seed/. Modify the file with the following code. Here, an object of the Faker class is created to generate fake data. The foreach loop is used to insert 100 fake records into the students table. A 5-digit random number will be generated for the std_id field. A fake name, fake email, and fake phone number will generate for the std_name, std_email, and std_mobile fields, respectively.

<?php

use Illuminate\Database\Seeder;

// Import DB facade and Faker service
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,100) as $index) {
                DB::table('students')->insert([
                'std_id' => $faker->randomNumber($nbDigits = 5) ,
                'std_name' => $faker->name,
                'std_email' => $faker->email,
                'std_mobile' => $faker->phoneNumber,
            ]);
        }
    }
}

Run the following command from the terminal to insert 100 fake records into the students table using database seeding.

$ php artisan db:seed

Open the students table to check whether the records are inserted into the table. You will get a similar output if the database seeding is done successfully.

Create a Controller to Read Data

Run the following command from the terminal to create a controller named StudentController.

$ php artisan make:controller StudentController

Open the controller and replace the code with the following code. Here, the paginate() function is called with the argument value 10 to display 10 records on each page. There are 100 records in the students table. So, 10-page links will be created in the view file to navigate the other records.

<?php

namespace App\Http\Controllers;
use App\Student;

use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function index(){
        $students = Student::paginate(10);
        return view('students', compact('students'));
    }
}

Create View to Display Data

Create a view file named students.blade.php with the following code. Here, the records of the students table will be displayed in tabular form. The link() function is called at the end of the table tag to display the pagination bar using bootstrap.

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Laravel Pagination Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://ift.tt/2EqpKUC
bootstrap.min.css">

</head>
<body>
<div class="container mt-5">
<center><h3 style="color:blue">Students List using Pagination</h3></center><br/>
<table class="table table-bordered mb-5">
<thead>
<tr class="table-info">
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile No.</th>
</tr>
</thead>
<tbody>
@foreach($students as $data)
<tr>
<th scope="row"></th>
<td></td>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>
</table>
<div class="d-flex justify-content-center">
{!! $students->links() !!}
</div>
</div>
</body>
</html>

Create Route for the Controller

Open the web.php file and add the following route to call the index() method of StudentController when the user types ‘students’ after the base URL.

Route::get('students', 'StudentController@index');

Now, open the following URL from the browser to display the output from the view.

http://localhost/laravelpro/public/students

You will get a similar output if the route works properly. The image below displays the first 10 records of the students table.

To display the last 10 records, press the link ’10’ from the pagination bar. It will display a similar output.

Conclusion

The Laravel framework makes the pagination task easier than in many other PHP applications. This tutorial showed you how to implement pagination with bootstrap in Laravel by using fake data for an example. If you are a new Laravel user and want to know how to implement pagination in your project, then this tutorial should help you learn how to do it.



from Linux Hint https://ift.tt/2HiMGGh

Post a Comment

0 Comments