laravel-user-pagination

Showing Paginated Records in Laravel: Example

Pagination in Laravel is very easy compared to other frameworks. Below is a step-by-step guide and the Laravel code to create a new page that shows a list of users in a paginated format with 10 users per page.

I have taken the example of User model, but you can create any model and do pagination for it. The model can be any entity that sits in the Database as a record like blog articles, new posts, transactions, etc.

With a very simple styling, this is how my Users page is looking after the code.

laravel-user-pagination

Introduction: Importance of Pagination

Pagination is a crucial feature in web development, especially when dealing with large datasets. By breaking down content into smaller, manageable pages, pagination enhances user experience by preventing information overload and making navigation easier. It also significantly improves website performance by reducing the amount of data loaded at once, leading to faster page load times and reduced server load. In Laravel, implementing pagination is straightforward, and it helps maintain a clean and efficient way of displaying large amounts of data seamlessly.

Code Example

This code sets up a new page in your Laravel application that displays a paginated list of users, with 10 users per page. The pagination links are automatically generated by Laravel’s pagination system.

Step 1: Create a Route

First, you need to define a route in routes/web.php.

// routes/web.php
use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index'])->name('users.index');

Step 2: Create a Controller

Next, create a controller to handle the request. You can generate a controller using the Artisan command:

php artisan make:controller UserController

Then, update the controller to fetch and paginate the users.

// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::paginate(10);
        return view('users.index', compact('users'));
    }
}

Step 3: Create a View

Create a Blade view to display the paginated list of users.

Create a new folder users in the resources/views directory if it doesn’t exist and then create an index.blade.php file inside it.

<!-- resources/views/users/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h2>List of Users</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>
    {{ $users->links() }}
</div>
</body>
</html>

Step 4: Ensure User Model Exists

Ensure that you have a User model. Laravel provides one by default when you create a new Laravel project.

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasFactory;

    // Add any necessary properties or methods
}

Step 5: Run Migrations

Make sure you have run the migrations to set up your database tables.

php artisan migrate

Step 6: Seed the Database (Optional)

If you need some dummy data for testing, you can seed your database.

php artisan tinker
// In the Tinker shell
\App\Models\User::factory()->count(50)->create();

This code sets up a new page in your Laravel application that displays a paginated list of users, with 10 users per page. The pagination links are automatically generated by Laravel’s pagination system.

Common Errors and Troubleshooting Tips

If you follow the example code the way I have explained, it should work for you wihtout any error. But below are some troubleshooting tips if you run into an error-

  1. Route Not Found:
    • Ensure your routes are defined correctly in routes/web.php.
    • Verify the URL in your browser matches the defined route.
  2. Undefined Variable:
    • Check if variables passed to views are correctly set in the controller.
  3. Pagination Links Not Displaying:
    • Ensure you are using {{ $users->links() }} in your Blade view.
    • Verify the User model has data.
  4. Query Parameter Issues:
    • Use withQueryString() to preserve query parameters during pagination.
  5. Database Connection Errors:
    • Check your .env file for correct database configuration.

Summary and Further Reading

In this article, we explored the importance of pagination in Laravel, discussed its implementation, and addressed common errors and troubleshooting tips. Pagination improves user experience by organizing data into manageable pages and enhances performance by reducing data load times.

For more detailed information, refer to the official Laravel documentation:

These resources provide comprehensive guides and best practices for efficient pagination in Laravel.