Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ksorbo's avatar

How to detect current page number when using paginate?

I have set up pagination for a large list of subscribers (over 7000); it working correctly. Each page shows a sub list of subscribers with an edit link for each. I am using a standard resource route; the edit button links to '/subscriber/<#id>/edit'

My question: Is there a way to detect which page the subscriber <#id> was on in the Subscriber::edit method? Paginate creates a url like:

/subscriber?page=3

My reason for doing this is that I want to save the page number and pass it on via hidden variable to the update method. Then I can redirect at the end of the update method to page the user back to the page he/she was on when they first hit the edit button. E.g. if subscriber being edited is on page 150, the user would be very frustrated when the system redirects back to /subscriber, which is page 1!

I suppose I could use a client side javascript to detect the page number on the uri and put it in a cookie or something like that. Doesn't seem very elegant solution!

**In summary: ** I want to be able to edit a user and when update is complete, redirect user back to the same page.

Final edit: My solution (below) was to set the client-side cookie and detect it and redirect. Not elegant, but simple and works.

0 likes
21 replies
ejdelmonico's avatar

From the docs...

By default, the current page is detected by the value of the page query string argument on the HTTP request.

ksorbo's avatar

@ejdelmonico I saw that bit of documentation.

However, it doesn't tell me how to access that info in my method. I have tried:

$request['page']

and it doesn't yield anything. I have even tried

$_REQUEST['page']

but it comes back empty each time. Seems to me that Laravel is emptying the $_REQUEST array before it gets to my controller method??

ejdelmonico's avatar

@ksorbo Use the toJson method to convert to json object. Check the JSON returned from the paginator in data. You should be able to access "current_page" key which contains the page number. In the docs, scroll down to "Converting Results To JSON".

ksorbo's avatar

@ejdelmonico

Thanks for your patience! (I am new at Laravel!)

I have studied the docs you refer to. Here is my index method:

    public function index(Request $request)
    {
        $queryBuilder = DB::table('subscribers')->select('id', 'name', 'email');

        $subscribers = $queryBuilder->paginate(20);

        return view('subscriber.index', compact('subscribers'));

My question is: how do I access the pagination object in my edit method? I assume the toJson is a method to apply to the pagination object created in the index method which doesn't exist any longer.

Confused...

ksorbo's avatar

@jekinney

I need to detect the page number in my edit method.

 public function edit(Paginator $paginate, Subscriber $subscriber)
    {
       $pagenumber = ?????? // HOW TO GET PAGINATER HERE.
        return view('subscriber.edit', compact('subscriber','pagenumber'));
    }

Are you suggesting that I requery the subscribers in the edit method? How would that work?

ejdelmonico's avatar

If the edit method is in the same controller, maybe use this at top: public $subscribers; and then in your index method, clean up the code with:

$subscribers = DB::table('subscribers')->select('id', 'name', 'email')->paginate(20);

That should make the $subscribers available to the edit method. Then, in edit something like: $subscribers->toJson();. You should be able to get the value or simply use $subscribers->currentPage() as a helper method.

All of the helper methods in each paginator instance are :

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (Not available when using simplePaginate)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (Not available when using simplePaginate)
$results->url($page)
8 likes
jekinney's avatar

as it's a post or put etc request:

<input type="hidden" name="page_on" value="{{ $results->currentPage() }}">
1 like
ksorbo's avatar

@ejdelmonico Here is my controller now. (You'll notice that I have included some search and sort parameters that I left out earlier)

class SubscriberController extends Controller
{
    public $subscribers;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $queryBuilder = DB::table('subscribers')->select('id', 'name', 'email');
        if ($request->has('search')) {
            $queryBuilder = $queryBuilder->Where('email', 'like', '%' . $request['search'] . '%')
                ->orWhere('name', 'like', '%' . $request['search'] . '%');
        }
        if ($request->has('orderby')) {
            $sort = $request->has('sort') ? $request['sort'] : 'asc';
            $queryBuilder = $queryBuilder->orderBy($request['orderby'], $sort);
        }
        $this->subscribers = $queryBuilder->paginate(20);
//        $subscribers->cnt = $cnt;

        if ($request->has('search')) {
            $this->subscribers->appends(['search' => $request['search']]);
        }
        if ($request->has('orderby')) {
            $this->subscribers->appends(['orderby' => $request['orderby']]);
            $this->subscribers->appends(['sort' => $sort]);
        }
        return view('subscriber.index', ['subscribers'=>$this->subscribers]);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $subscriber = Subscriber::findOrFail($id);
        return view('subscriber.show', compact('subscriber'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit( Subscriber $subscriber)
    {
        dd($this->subscribers);
        $listofsublists = Sublist::orderBy('listname')->pluck('listname','id')->toArray();
        return view('subscriber.edit', compact('subscriber','listofsublists'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Subscriber $subscriber)
    {
        $subscriber->update($request->all());
        $subscriber->sublists()->sync($request->input('sublists'));
        return back();
//        return redirect('subscriber/'.$subscriber->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

notice dd($this->subscribers); in edit method.

This return null.

ejdelmonico's avatar

Ok, I see I think you what to die and dump the $subscribers. However, you don't return $subscribers anywhere so maybe extract that and return it. Then, you should have it available. Or, to rethink your approach cause index is a bit messy. You can use a scope on the model to return the data you want.

1 like
jlrdw's avatar

You can also get that URI segment.

ksorbo's avatar
ksorbo
OP
Best Answer
Level 8

Here is how I solved the problem. Not sure if it is elegant enough for Laravel, but I can't find another way.

In my index.blade.php display which displays all the subscribers, I added a client side cookie which saves the entire list of get variables on the URL.

    <script>
        document.cookie="pageurl=" + encodeURIComponent(window.location['search']);
    </script>

Then when all updates are properly processed and saved in my update (and create method), I redirect thus:

        return redirect('subscriber'.$_COOKIE['pageurl']);

I am aware that this does not use the Laravel cookie function, but since Laravel assumes that all cookies are encrypted, I see how you could possibly create a Laravel-compatible encrypted cookie on the client side.

I had originally thought to pass the information to the edit method and then on to the update method, but since all I need it for is the final redirect, I saved it locally as a cookie and then redirected the user to where he/she was at when he/she started the edit process. This preserves the page the user was on plus any search and/or sort parameters added.

I imagine there must be some safety issue here, but I am not aware of it.

1 like
Snapey's avatar

late to the party...

since in Laravel you can redirect->back() it stands to reason that the framework is noting the referrer.

You should be able to just grab that referrer in your edit function and pass it into the edit form, or save it to a server side session variable.

after your update, redirect to the original referrer.

1 like
ksorbo's avatar

thanks, @Snapey

This is a better approach. It still entails saving the url, but in this way I can save it to a session variable, rather than a clientside generated cookie.

Snapey's avatar

When hitting the edit page;

session('currentPage' => $request->server('HTTP_REFERER'));

after editing the account;

return redirect(session('currentPage');

(or something like that)

2 likes
flienky's avatar

You can use

\Illuminate\Pagination\Paginator::resolveCurrentPage($pageGETparamName) which returns the current page.

1 like
ava242's avatar

i found out to accessing current page when using pagination method on laravel. here is my code :

public function index(Request $request) { $queryBuilder = DB::table('subscribers')->select('id', 'name', 'email');

    $subscribers = $queryBuilder->paginate(20);
$data = json_decode($subscribers ->toJSON());

    return view('subscriber.index', ['subscribers' => $subscribers, 'current_page' => $data->current_page]);

}

1 like
bansal's avatar

Try this:

var current_page = $(".pagination").find('.active').text();
1 like
MrMoxy's avatar

I struggled a long time to figure this out as well. But it turns out it's brilliantly simple. Laravel automatically generates the pagination in your view with

{{ $subscribers->links() }}

To get the current page in your view, just use

{{ $subscribers->getCurrentPage(); }}

Then you can either append the page # to your url like this:

<a href="/subscriber/edit/1234/?page={{ $subscribers->getCurrentPage(); }}">Edit subscriber 1234</a>

or you can insert it as a post variable

<input type="hidden" name="page_on" value="{{ $subscribers->currentPage() }}">

HTH.

1 like

Please or to participate in this conversation.