Create Custom Pagination with Pretty URL in Laravel

Hello Artisan,

In this tutorial, I will share with you how to create Laravel pagination without query string. In this tutorial, our challenge is we have to create a pretty pagination URL in Laravel. That means no query string with pagination.

You know that Laravel default pagination pattern is http://xyz.com?page=2. But we want to make it like http://xyz.com/page/2

You know that this pagination without query string is more SEO-friendly and looks pretty. So let's see how we can create Laravel pagination pretty url without query string.

 

Step 1: Create Route

In this step, we need to create our paginated route. So update your web.php like below:

Route::get('users/page/{id}', 'TestController@index');

 

Step 2: Create Controller

Now generate some fake users so that we can make and test our pretty url pagination in laravel. This pagination looks like WordPress pagination. Now update your test controller.

app\Http\Controllers\TestController.php

namespace App\Http\Controllers;

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

class TestController extends Controller
{
    public function index($id)
    {   
        $paginate = 8;
        $skip = ($id*$paginate)-$paginate;
        $prevUrl = $nextUrl = '';
        if($skip>0){
            $prevUrl = $id - 1;
        }
        $users = User::orderBy('id', 'desc')->skip($skip)->take($paginate)->get();
        if($users->count()>0){
            if($users->count()>=$paginate){
                $nextUrl = $id + 1;
            }
            return view('welcome', compact('users', 'prevUrl', 'nextUrl'));
        }
        return redirect('/welcome');
    }
}

 

Step 3: Create View

We are in the final step. Just we need to create our welcome view to see our laravel pagination without query string that means pretty pagination in laravel.

resources\views\welcome.blade.php

 

Read also: Laravel 8 Custom Pagination Tutorial

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js