ShadCn UI kit now on producthunt
Skip to content
UI Lib Blog

Effortless Pagination With Laravel!

Manual pagination is a very tedious job for any developer. But with Laravel, there is no need to write any extra code for paginating your data! At UI-Lib, we believe Laravel is always there to save our day from writing complex codes. And as always, Laravel has never underestimated us. When it came to data pagination, Laravel took the responsibility to take care of the pagination side. And doing so, helped us focus more on handling our data and effortlessly paginate them.

We all know what pagination is. It basically means separating our contents both in print or in digital form into discreet pages. But like Laravel we at UI-Lib try our best to make you understand anything we write, effortlessly. So for the newbies, by saying pagination we mean the thing shown in the image below,

pagination laravel

Now let us understand how we can easily paginate our data. For this, we need to perform the following steps

  1. Creating Project with Laravel
  2. Database Configuration
  3. Defining and Migrating Model
  4. Fake Data Generation
  5. Controller and Route Creation
  6. Create View File
  7. Use Pagination
  8. Run Laravel Application

Let’s dive into the process where we can see how easily we can use pagination in our project with Laravel,

Creating Project Laravel-Pagination With Laravel

To practically understand how pagination is made easy with Laravel we first need to create a project with Laravel. Creating a project with Laravel is achieved with just one command,

composer create-project laravel/laravel laravel-pagination

Now our project folder is created. To work on our project we need to go inside the project directory,

cd laravel-pagination

Database Configuration

Next, we need to configure our .env file inside the project folder. We need to start a local server on our local development system. For that, we are using XAMPP. Now we need to add the database configuration in our .env file to establish a connection between Laravel and MySQL.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=password

As a reminder, you need to create a database named “laravel_db” to work with the above code.

Defining and Migrating Model

We are at the stage now where we should start building our model. A model basically means the logical structure of a table in our database. By the following command, Laravel will automatically generate a Model named Student.

php artisan make:model Student -m

-m means Laravel will also create a migration file where we can define the columns of the Student table. In the database/migrations/timestamp_create_students_table.php file let us define the following columns in the up method,

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('firstname');
        $table->string('lastname');
        $table->string('email')->unique();
    });
}

Now in the app/Models/Student.php file, we should add the fillable array so that we can add values to the columns.

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',
    ];
}

Now we are ready to migrate,

php artisan migrate

Fake Data Generation For Laravel Pagination

Pagination is a process where we can display a large amount of data in groups. For that, we need to generate a load of data. Faker a built-in package provided by Laravel can come in handy now. Faker helps to create a specific amount of fake data to start working on our project.

In the database/seed/DatabaseSeeder.php file let us write the following code,

use Illuminate\Database\Seeder;
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,1000) as $index) {
            DB::table('students')->insert([
                'firstname' => $faker->firstname,
                'lastname' => $faker->lastname,
                'email' => $faker->email,
            ]);
        }
    }
}

The above code will generate 1000 fake data in the Student model. For that, we need to run the command below,

php artisan db:seed

Controller and Route Creation

We are ready to create our controller file by the following command,

php artisan make:controller StudentsController

Now we should start building the logic inside the controller file we created,

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentsController extends Controller
{
    public function getStudentData(){
      $students = Student::all();
      return view('home', compact('students'));
    }
}

Lastly, we define the route that will help us render the view file. In the routes/web.php file,

use App\Http\Controllers\ StudentsController;

Route::get('/', [StudentsController::class, 'getStudentData']);

The above code will display the home.blade.php file in the browser.

Create View File To Display Laravel Pagination

We now create a home.blade.php file and show the data from our Student model.

<!DOCTYPE html>
    <html>
    <head>
        <title>Laravel Pagination</title>
    </head>
    <body>
        <div>
            <table>
                <thead>
                    <tr>
                        <th">#</th>
                        <th>First name</th>
                        <th>Last name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($students as $student)
                    <tr>
                        <th>{{ $student->id }}</th>
                        <td>{{ $student->firstname }}</td>
                        <td>{{ $student->lastname }}</td>
                        <td>{{ $student->email }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </body>
</html>

Use Laravel Pagination

In this step, the interesting and the most effortless thing begins. Previously for creating pagination we needed to manually write a code for paginating data. Now you will be amazed to know that we just need to do a simple thing for pagination. In the StudentsController.php file where we defined all() method we just need to change that and call the paginate() method. paginate() takes a simple integer value which will indicate how much data to show on a single page.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentsController extends Controller
{
    public function getStudentData(){
      $students = Student::paginate(25);
      return view('home', compact('students'));
    }
}

The above code will show the first 25 student’s data in the view file and add a pagination bar that will link the other student’s data. But to do that in the home.blade.php we should add the following code,

 {!! $students->links() !!}

The entire home.blade.php the file will look like below,

<!DOCTYPE html>
    <html>
    <head>
        <title>Laravel Pagination</title>
    </head>
    <body>
        <div>
            <table>
                <thead>
                    <tr>
                        <th">#</th>
                        <th>First name</th>
                        <th>Last name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($students as $student)
                    <tr>
                        <th>{{ $student->id }}</th>
                        <td>{{ $student->firstname }}</td>
                        <td>{{ $student->lastname }}</td>
                        <td>{{ $student->email }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
          {!! $students->links() !!}
        </div>
    </body>
</html>

Thus, just like that, we can add pagination to our Laravel project.

Run Laravel Application

Finally, to see what we created we should run the Laravel application with the following command and check the result on the URL http://127.0.0.1:8000,

php artisan serve

Conclusion

Laravel, for us, is an amazing web framework. For this reason, we are always eager to explore what features we can achieve from it. As a result, we stumble upon many exciting functionalities. And, that is why we can bring you new blogs and products every day.

Pagination was a nightmare for us previously, running a loop for a certain number of times and then decorating the pagination style. However, Laravel thought about us and tried its best to solve this issue. And, we can say with certainty, that it has completely made pagination effortless for us.

Our Products Based on Laravel

2. WorkTick – Ultimate HRM & Project Management Software

3. Stocky – Ultimate Inventory Management System with Pos

4. Gull – Bootstrap & Laravel Admin Dashboard Template

Relevant Articles

Comments are closed, but trackbacks and pingbacks are open.