1

I would like to return to a view with compact variable with paginate.

public function detail(Request $request){

    $data = DATA::paginate(10);
    $lastPage = $data->lastPage(); //How to use this variable?

    return view('user.data', compact('data'));
}

The default of this paginate will go to first page.

How do I use lastPage variable to go to last page by default?

Kelvin Low
  • 390
  • 6
  • 22
  • Please give us a bit more information about what exactly you want. Why don't you simply use `$data->lastPage();` in your view? – tinyoverflow Oct 30 '17 at 05:44
  • I have a view page will display `$data` as paginate. This might be more than 1 page, I would like my user go directly to the last page when he is browsing this view. – Kelvin Low Oct 30 '17 at 05:58
  • For example, I have 15 items and my paginate is 10. There will be 5 items in 2nd page. I would like my user to view the last 5 items on 2nd page by default when he being routed to my view. Can you tell me how do I use `$data->lastPage()` in my view? – Kelvin Low Oct 30 '17 at 06:00

2 Answers2

4

By using Paginator::currentPageResolver is able to redirect to a view and go the last page by default.

public function detail(Request $request){

    if($request->page == '') {
        $lastPage = Model::paginate($paginate)->lastPage();
        Paginator::currentPageResolver(function() use ($lastPage) {
            return $lastPage;
        });
    }

    $data = Model::paginate($paginate);
    return view('user.detail', compact('data'));
}

The main point is to set if condition to prevent stuck on a same page when user is switching pages.

Kelvin Low
  • 390
  • 6
  • 22
  • This works well, but is there a way to do this without having to query twice? For example if using a raw query we would have taken the last n records. – Ahmed Shefeer Apr 19 '20 at 07:52
0

You instead pass your $lastPage variable to the view.

jjjmnz
  • 49
  • 1
  • 6
  • How do I do it? Can you tell me more detail about it? Thank you =) – Kelvin Low Oct 30 '17 at 01:34
  • One way I could think of is instead of passing the $data variable to your view, go pass the $lastPage variable. On your view, you should have a script that automatically changes the selected page on your pagination, as it would default on the first page. – jjjmnz Oct 30 '17 at 01:37
  • Another way would be to call one of the static methods of the Paginator class. [Check it out here.] (https://stackoverflow.com/questions/31747801/laravel-5-1-specifing-current-page-for-pagination) – jjjmnz Oct 30 '17 at 01:38