Laravel Next Previous Link Button Pagination
Laravel Next Previous Link Button Pagination

Laravel Next Previous Link Button Pagination

Laravel is a popular PHP framework that makes web development a breeze. One of its features is pagination, which helps in displaying large sets of data in a user-friendly manner. In this article, we will focus on creating simple “Next” and “Previous” buttons for pagination in Laravel. We’ll walk through the process step-by-step with easy-to-follow code examples.

Step 1: Setting Up the Project

First, ensure you have Laravel installed. If not, you can install it using Composer:

composer create-project --prefer-dist laravel/laravel blog

Navigate to your project directory:

cd blog

Step 2: Creating a Model and Migration

Let’s assume we are paginating through a list of posts. We’ll create a Post model and migration.

Run the following command to generate the model and migration:

php artisan make:model Post -m

Now, open the migration file (database/migrations/xxxx_xx_xx_create_posts_table.php) and define the schema:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

Step 3: Seeding the Database

To have some data to work with, let’s create a seeder.

Run the following command:

php artisan make:seeder PostSeeder

Open the seeder file (database/seeders/PostSeeder.php) and add some dummy data:

use App\Models\Post;
use Illuminate\Database\Seeder;

class PostSeeder extends Seeder
{
    public function run()
    {
        Post::factory()->count(50)->create();
    }
}

Also, create a factory for generating dummy posts:

php artisan make:factory PostFactory --model=Post

In the factory file (database/factories/PostFactory.php), define the factory:

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    protected $model = Post::class;

    public function definition()
    {
        return [
            'title' => $this->faker->sentence,
            'content' => $this->faker->paragraph,
        ];
    }
}

Now, run the seeder:

php artisan db:seed --class=PostSeeder

Step 4: Setting Up the Controller

Create a controller for handling the post display and pagination:

php artisan make:controller PostController

In the controller file (app/Http/Controllers/PostController.php), add the following code:

use App\Models\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::paginate(5);

        return view('posts.index', compact('posts'));
    }
}

Step 5: Creating the View

Create a Blade view to display the posts and pagination buttons.

Create a directory and file for the view (resources/views/posts/index.blade.php):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Posts</title>
</head>
<body>
    <h1>Posts</h1>
    <ul>
        @foreach($posts as $post)
            <li>
                <h2>{{ $post->title }}</h2>
                <p>{{ $post->content }}</p>
            </li>
        @endforeach
    </ul>

    <div>
        @if ($posts->onFirstPage())
            <span>&laquo; Previous</span>
        @else
            <a href="{{ $posts->previousPageUrl() }}">&laquo; Previous</a>
        @endif

        @if ($posts->hasMorePages())
            <a href="{{ $posts->nextPageUrl() }}">Next &raquo;</a>
        @else
            <span>Next &raquo;</span>
        @endif
    </div>
</body>
</html>

Step 6: Defining the Route

Open the routes/web.php file and define a route for the posts:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);

Step 7: Testing the Pagination

Start the Laravel development server:

php artisan serve

Open your browser and navigate to http://localhost:8000/posts. You should see a list of posts with “Next” and “Previous” buttons for pagination.

Conclusion

You’ve now set up simple pagination in a Laravel application with “Next” and “Previous” buttons. This is a basic example, but you can customize and extend it further based on your needs. Laravel’s pagination is flexible and powerful, making it easy to implement in any project.