Reputation: 27
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
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');
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