Reputation: 936
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.
Upvotes: 2
Views: 994
Reputation: 702
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.
class SomeClass
{
public function __construct(private Service $service) {}
public function call()
{
$data = [
'variable_a' => 'string',
'variable_b' => true,
];
$request = CustomFormRequest::create('', '', $data)
->setContainer(app())
->validateResolved();
$return_data = $this->service->project($request);
}
}
class Service
{
public function project(CustomFormRequest $request)
{
$validated = $request->validated();
// other stuff
}
}
Upvotes: 0