skip to Main Content

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: enter image description here

But when I change the TestRequest to just a regular Request, it works normally.

What am I missing using my custom TestRequest?

2

Answers


  1. The method you have on the print is GET, and your route in api.php is POST.

    Login or Signup to reply.
  2. 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 :

    $validated = $request->validated();
    

    I hope this can help

    /**
      * Register a new user
      * @param TestRequest $request
      * @return void
      */
    public function register(TestRequest $request): array
    {
        // The incoming request is valid...
     
        // Retrieve the validated input data...
        $validated = $request->validated();
    
        // Store data...
        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search