I need to create a custom request on the fly and pass the request to the Form Request. The closest answer that I found was this SO answer. However when I run $request->validated(), it gives me error message Call to a member function validated() on null in /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:221.
Below is the whole code:
Function A
private $service;
public function __construct(
Service $service,
) {
$this->service = $service;
}
...
$data = [
"variable_a" => "string",
'variable_b' => true,
];
$request = new Request();
$request->replace($data);
$customFormRequest = new CustomFormRequest();
$validate = $customFormRequest::createFrom(
$request
);
$return_data = $this->service->project($validate);
Service
public function project(CustomFormRequest $request)
{
\Log::debug($request);
$data = $request->validated();
\Log::debug($data);
}
Note
$request and $request->all() has array values when logging inside Service.
The reason it doesn't work is because you are only getting an instance of the CustomFormRequest. Custom form requests are only validated when they are resolved out of the container.