Pagination + URL Params in Laravel 7

China☆狼群 提交于 2020-04-17 20:06:14

问题


If I go to http://app.test/visitor?interval=week, I will see this

Issue 🐞

As soon as I clicked on the second one, I got redirected to : http://app.test/visitor?page=2

It removed my interval=week, which ruined my query view for my weekly views.


Code

This is how I construct my page

public function index()
{
    $inputs    = Request::all();
    $interval  = '';

    if(array_key_exists('interval', $inputs)){
        $interval  = $inputs['interval'];
    }

    switch ($interval) {
        case 'day':
        $visitors = Visitor::where('created_at', '>', now()->today())->paginate(10);;
        break;
        case 'week':
        $visitors = Visitor::where('created_at', '>', now()->subMonth())->paginate(10);;
        break;
        case 'month':
        $visitors = Visitor::where('created_at', '>', now()->subMonth())->paginate(10);;
        break;
        case 'year':
        $visitors = Visitor::where('created_at', '>', now()->subYear())->paginate(10);
        break;
        default:
        $visitors = Visitor::orderBy('updated_at', 'desc')->paginate(10);
        break;
    }


    return View::make('layouts.be.visitors.index', get_defined_vars());
} 

View

{!! $visitors->render() !!}

Goal

is to stay in the same view, with something like this

http://app.test/visitor?interval=week&page=2

Do I have to overwrite the default pagination function?

How do I solve this issues ?


回答1:


Your solution works but there is a built-in method for achieving your desired result in Laravel 7.

{{ $visitors->withQueryString()->links() }}

You can see your exact problem being solved in the attached PR: https://github.com/laravel/framework/pull/31648

FYI, links() replaced render() in Laravel 5.3




回答2:


I think I found the answer to it. I updated my view

{!! $visitors->render() !!}

to

{!! $visitors->appends(Request::except('page'))->render() !!}

It doesn't replace my current URL params anymore.



来源:https://stackoverflow.com/questions/61193833/pagination-url-params-in-laravel-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!