Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a POST route in Laravel

Tags:

In my controller, I have a method which should redirect to a POST route. I can not make this route a GET one either. Is there any solutions?

My controller code looks like:

// After a bunch of other if statements, etc
return redirect('newUser')->with('user', $user);

Now my route (in web.php) is as follows:

Route::post('/newUser', function() {
    $user=session('user');
    dd($user);
    return view('profileNewUser', $user);
});

The error which is thrown at me is MethodNotAllowedHTTPException.

I know my error is something to do with the _token, is there anyway I can allow the token field to get passed on? I tried passing it in with the with in my redirect but that doesn't work either.

Thanks for your help.

like image 991
Muhammad Avatar asked Aug 01 '17 16:08

Muhammad


2 Answers

Try redirect to Named Route.

Route::post('/newUser', function() {
    $user=session('user');
    dd($user);
    return view('profileNewUser', $user);
})->name('newusr');

Then:

return redirect()->route('newusr', ['user'=>$user]);

Or, redirect to controller actions.

  • See this tutorial about redirects: http://coursesweb.net/laravel/redirects
like image 110
CoursesWeb Avatar answered Oct 07 '22 00:10

CoursesWeb


Since you need the url to be 'newUser' then you can simply make a GET route of the same url.

The question as to Why you would want to return the post request to the same route is still valid, because it might lead to infinite call of the same route.

One way however, is you can add a logic to check if user is already in session then do otherwise, else this kind of pattern is not really good.

Best way is to separate your page that returns the response of your POST from the one that renders a view.

Like I suggested in the comment: you can simply move this getUser route into a controller then use Laravel's Response to action or the other way. Here is the answer in case you want to browse.

PS: my answer is based on my understanding of your question. Thank you.

like image 25
Oluwatobi Samuel Omisakin Avatar answered Oct 07 '22 01:10

Oluwatobi Samuel Omisakin