Saibal Kabir
Saibal Kabir

Reputation: 27

How to beautify pagination URL in laravel 6.x

I have a website where I used pagination . But the url is making pagination url such as

http://website.com/user?page=2

But I want to beautify it as

http://website.com/user/2

I am using laravel 6. how can I make it to do?

Upvotes: 0

Views: 628

Answers (1)

Saibal Kabir
Saibal Kabir

Reputation: 27

Pretty Laravel Pagination

There is no official way to beautify laravel pagination code. So I make my own code and Finally it is working.

Goal

www.website.com/user?page=1 → →→→ www.website.com/user/1

Step1:

In route :

Route::get('/user/{page?}', 'MainController@index')->where('page', '[0-9]+')->name('areasearch');
  • where('page', '[0-9]+') this code is to maintain that page parameter will accept only numeric value.
  • {page?} here ? question mark is for making the value optional.

Step2: In MainController:

public function index(Request $request){
    if(isset($request->page) && $request->page<1)
        $page = 1;
    else
        $page = $request->page;
    $user = User::ALL();
    $data=$this->paginateArray(user,$page);
    $data=$data->setPath($request->url());
    return view('index')->with('data',$data);
}
public function paginateArray($user='', $page = 1)
    {
    $currentPage = $page;
    $user_collection = collect($user);
    $perPage = 50;
    $paginatedItems = new LengthAwarePaginator($user_collection->forPage($currentPage, $perPage) , $user_collection->count(), $perPage, $page);
    return $paginatedItems;
    }
public function paginate_with_custom_path($data)
    {
    $links = $data->links('pagination.paginator');
    $patterns = '#\?page=#';
    $replacements = '/';
    $one = preg_replace($patterns, $replacements, $links);
    $pattern2 = '#/([1-9]+[0-9]*)/([1-9]+[0-9]*)#';
    $replacements2 = '/$2';
    $paginate_links = preg_replace($pattern2, $replacements2, $one);
    return $paginate_links;
    }

Step3: In view:

use App\Http\Controllers\MainController; $MainController= new MainController(); 
@extends('master')
@section('maincontent')
    {!!$MainController->paginate_with_custom_path($data)!!}
@endsection

That's all . We successfully made changes the url.

Upvotes: 0

Related Questions