Laravel Custom Request Is not woring

96 Views Asked by At

So I was trying to use Laravel custom request, following the documentation:

api.php

Route::post('/register-user', [AuthController::class, 'register']);

AuthController.php

namespace App\Http\Controllers;

use App\Http\Requests\TestRequest;
use Illuminate\Routing\Controller 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 App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

There are 2 best solutions below

1
francisco On

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

1
Paul J.K On

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...
    
}