phplaravellaravel-5eloquent

How to redirect paginate to current page?


I have set up pagination and it's working correctly. But i am not able to redirect to the current page.

E.g: If i invoke update method on currencies?page=2. I will redirect to the currencies instead of currencies?page=2.

Controller - index function

public function index()
{
    $currencies = Currency::paginate(5);
    return view('admin.currencies.index')
            ->withCurrencies($currencies);
}

Controller - Edit function

public function edit($id)
{
    $currency = Currency::findOrFail($id);
    return view('admin.currencies.edit')
            ->withCurrency($currency);
}

Controller - Update function

public function update(Request $request, $id)
{
    $currency = Currency::findOrFail($id);
    $currency->name     =   $request->name;
    $currency->rate     =   $request->rate;
    $currency->save();

    return redirect()->route('currencies.index')->with('message', 'Done');
}

Views

{{ $currencies->links() }}


Solution

  • Check out the documentation here https://laravel.com/docs/5.5/pagination#paginator-instance-methods

    You can either keep track of the page number (from referral URL if update is on different page or from query param) and pass that along in your update function like this instead of redirecting to a route.

    //$page =  grab page number from the query param here.
    return redirect('currencies?page='.$page);
    

    or you can also modify your index controller where you pass the page number as optional param and if null default to page 1 and if present pass that in.

    $results->url($page)
    

    Good luck.