So I was trying to use Laravel custom request, following the documentation:
api.php
Route::post('/register-user', [AuthController::class, 'register']);
AuthController.php:
namespace AppHttpControllers;
use AppHttpRequestsTestRequest;
use IlluminateRoutingController as BaseController;
class AuthController extends BaseController
{
/**
* Register a new user
* @param TestRequest $request
* @return void
*/
public function register(TestRequest $request): array
{
dd($request);
}
}
TestRequest.php
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class TestRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'required|string',
];
}
}
when I make a post request to this route, my $request object is just all empty. as you can see:
But when I change the TestRequest to just a regular Request, it works normally.
What am I missing using my custom TestRequest?
2
Answers
The method you have on the print is
GET
, and your route inapi.php
isPOST
.Form requests are custom request classes that encapsulate their own validation and authorization logic. The incoming form request is validated before the controller method is called.
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display.
If you want to retrieve the validated input data, you can use :
I hope this can help