There is a problem occurring while using APIs with trailing slash.
Route
Route::post('user/register','UserController@register');
It's working fine when I called this route POST
from the postman/website, but I called this route from mobile with a trailing slash like the following.
user/register/
Laravel, by default, remove the trailing slash but make the request as GET
when I dump the request method.
$method = $_SERVER['REQUEST_METHOD'];
$json = json_encode(['response' => $method], true);
result -> "{response : 'GET'}"
And I am unable to fetch the request body.
NOTE: I have tried many solutions but couldn't find any solution, and also, I can't remove or update route calling from the mobile end, so I have to handle it on the server-side.
When Laravel detects a trailing slash, it returns a 301 redirect to an "untrailed slash" version. The redirected request is always 'GET', so you won't be able to get the POST result.
The only way to prevent this (assuming you're using Apache) is go to your .htaccess file (should be in the public directory of your laravel installation) and remove the following:
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
Now the URLs with trailing slashes won't be redirected anymore.
EDIT: If you want to prevent redirects of only certain URIs, instead of removing those lines, you need to specify a stricter condition. For example, to stop redirecting only the links containing "customer", you'll do this:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !customer
RewriteRule ^ %1 [L,R=301]
and only the links not containing "customer" anywhere will be redirected.