Tim
Tim

Reputation: 5943

After submitting form redirect back to previous page in Laravel

I have a controller which is routed through Route::controller().

I have a getEdit and a postEdit function. I'm linking to the getEdit-function from different locations and want the user to be redirected TO that location after making changes within the form and submitting it.

I used the Redirect::back() method after successfully saving to the database but unfortunately I don't get redirected to the requested page BEFORE getEdit but instead get back to getEdit.

Do I have the possibility to change that behavior?

Upvotes: 1

Views: 6580

Answers (3)

stardust4891
stardust4891

Reputation: 2550

You can also do this via a middleware:

<?php

namespace Kjjdion\Larapack\Http\Middleware;

use Closure;

class IntendUrl
{
    public function handle($request, Closure $next)
    {
        // set intended url for redirect
        $request->session()->put('url.intended', $request->url());

        return $next($request);
    }
}

Then simply call the middleware in your controller construct for the methods you want to store for redirection.

Upvotes: 0

Tim
Tim

Reputation: 5943

After searching and trying I came up with a solution which seems to be perfect for my scenario and seems also pretty clean to me.

Instead of using URL parameters or any of that kind I simply set the Session key url.intended to URL::previous() in my getEdit function.

Session::put('url.intended', URL::previous());  // using the Facade
session()->put('url.intended', URL::previous(); // using the L5 helper

Within my postEdit function I simply do a return Redirect::intended('/').

Works like a charm and solves my issue completely.

Upvotes: 13

thatnetworkguy
thatnetworkguy

Reputation: 153

To add an example using Laravel 5 to Tim's answer:

In your controller methods that have an edit form:

Session::put('requestReferrer', URL::previous());

This will store the URL of the previous page that linked to the edit form as a session var requestReferrer.

To have your update method redirect back to this variable:

return redirect(Session::get('requestReferrer'));

I'm assuming if more than one form is open at once by the user that this may not give the expected behavior. If someone suggests a better revision I will edit this post to include it.

Upvotes: 1

Related Questions