naneri
naneri

Reputation: 3971

How to correctly redirect after doing POST in Laravel?

I have multiple routes with comments and when I click reply I get redirected to a route where I can post a reply to a comment. How can I correctly store the route from where I came and then redirect back to it after posting the reply?

I considered passing the URL::previous as a param and storing it into a hidden input, but if the page gets refreshed by the user it gets empty. Another way might be store in the session, but then I don't know how to reliably expire it...

Upvotes: 1

Views: 223

Answers (8)

Komal
Komal

Reputation: 2736

Do like this,

First store url in session

$request->session()->put('previous-url', '/user/demo'); 

Use like this

$previous_url = Session::get('previous-url'); 
return redirect()->to($previous_url);

Upvotes: 0

Vikash
Vikash

Reputation: 3551

Simply you can do return redirect()->back();

Upvotes: 0

Komal
Komal

Reputation: 2736

Redirect back with success message

return redirect()->back()->with('success', 'Data added successfully');

Upvotes: 2

Store url in the session when user access page, when you have your reply button. You dont have to expire it, it will get automaticaly updated when user visit next page with reply button.

session(['last_url' => 'Request::fullUrl()']);

Also dont forget to use namespace

Use Request;

If you really want to discard value from session after user redirects, you can use this:

return redirect()->url(Session::pull('last_url'));

And namespace

Use Session;

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You can keep 2-3-4-5 URLs in a session and you don't need to expire it. You can just limit number of kept URLs. Also, please check my answer to a similar question here.

Upvotes: 0

Md Nozibulla Bashar
Md Nozibulla Bashar

Reputation: 675

use return redirect()->back();

Upvotes: 1

Ganesh
Ganesh

Reputation: 3428

You can use return Redirect::back(); or return Redirect::to(URL::previous() . "#whatever");

Upvotes: 0

Gulmuhammad Akbari
Gulmuhammad Akbari

Reputation: 2036

Use return Redirect::back() function for the previous URL.

Upvotes: 0

Related Questions