I have got a problem with Laravel.
I have created a custom Form Request - let's call it CustomFormRequest. It is authorized and have got rules as it should be.
In one of the classes I use this request this way:
class CustomClass {
public function __construct(CustomFormRequest $customFormRequest) {
// Code only run from there after a successful validation.
// If there was an error in validation then HTTP 422 error was send by Laravel
}
}
From a Controller, usually I use this CustomClass in this way:
public function Custom(CustomClass $customClass) {
// Code only run from there after a successful validation.
}
But, sometimes, I also try to access this class in this way from either a controller or from other class:
$customRequest = new CustomRequest();
$customRequest->sendMethod('POST');
$customRequest->request->add(...array of data...);
new CustomClass($customRequest);
But it turned out when I use the class this way Laravel somehow skips the validation and even when I gave an invalid data for the class, it will run and tries to put those invalid data into the database!
Is there anything that I missing!? Is another line needed to enforcing the validation!?
Thanks for any further help!
I also tried using $request->validate($request->rules()) but it leads to ERR_TOO_MANY_REDIRECTS.
---------------------------------- Edit ----------------------------------
Thanks @matthew-bradley! #2 worked for me with changes:
From this:
$data = [...];
$validator = Validator::make($data, (new CustomRequest())->rules());
To this:
$data = [...];
$request = new CustomRequest();
$request->setMethod('POST');
$request->request->add($data);
$validator = Validator::make($data, $request->rules());
Reason for changes:
When using new CustomRequest())->rules() then $this->request->get(...) does not receive $data at all inside the rules() of CustomRequest()!
And I need those $data for my CustomRule() for further validation.
So first we should create a new CustomRequest with adding our data to it.
Then as the second parameter of Validator::make() we should use $request->rules() instead of new CustomRequest())->rules() so $this->request->get(...) finally can receive the $data.
---------------------------------- Edit 2. ----------------------------------
And after doing $validator:
if($validator->fails()) {
response()->json(['errors' => $validator->messages()->getMessages()], 422)->send();
die;
} else {
new CustomClass($request);
};
The issue with your original implementation was using $request->validate
as, by default, this will return a redirect. See here from the laravel docs about why this happens.
There are two ways to rectify this.
failedValidation
method on the FormRequest
class to conditionally check what output is expected from the request. This may work for some cases but we should alternatively do:$data = [...]; //This could be your request, or some other data
$validator = Validator::make($data, (new CustomRequest())->rules());
if ($validator->fails()) {
// Do something
}