Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel. Redirect intended to post method

I'm using laravel 5 and this is my problem. User fill in form X and if he isin't logged in, he gets redirected to fill in more fields form OR he gets possibility to log in. Everything works just fine, if user fill in additional fields, but if he login, laravel redirects user to form X with GET method instead of POST.

This is how my middleware redirect looks like:

return redirect()->guest('user/additional-fields');

This redirect appears on successfull log in:

return redirect()->intended();

So on redirect intended i get error MethodNotAllowedHttpException. URL is correct which is defined as POST method. What am I missing here? Why does laravel redirects intended as GET method? How could I solve this problem? Thanks!

EDIT:

Route::post('/user/log-in-post', ['as' => 'user-log-in-post', 'uses' => 'UserController@postUserLogIn']);

This is my route, I hope this is one you need.

like image 876
Evaldas Butkus Avatar asked Feb 11 '23 00:02

Evaldas Butkus


2 Answers

You can use a named route to solve this issue:

Lets make a named route like this:

For Get

Route::get('user/additional-fields',array(
    'uses' => 'UserController@getAdditionalFields',
    'as'   => 'user.getAdditionalFields'
));

For post

Route::post('user/additional-fields',array(
    'uses' => 'UserController@postAdditionalFields',
    'as'   => 'user.postAdditionalFields'
));

So we can now ensure Laravel uses the right route by doing this

return redirect()->guest(route('user.getAdditionalFields'));

Also note that its not possible to redirect a POST because Laravel expects form to be submitted. SO you can't do this:

return redirect()->guest(route('user.postAdditionalFields'));

except you use something like cURL or GuzzleHttp simulate a post request

like image 154
Emeka Mbah Avatar answered Feb 12 '23 12:02

Emeka Mbah


You have to trick Laravel router by passing an "_method" the inputs.

The best way I found is by adding tricking and rewriting the Authenticate middleware

You have to rewrite the handle method to allow your redirection with your new input.

redirect()->guest('your/path')->with('_method', session('url.entended.method', 'GET'));

When you want to redirect to a route using another method than GET, simply do a Session::flash('url.entended.method', 'YOUR_METHOD').

Tell me if it do the trick

like image 35
ChainList Avatar answered Feb 12 '23 14:02

ChainList