How do i use the prepareForValidation? (laravel 8)
the prepareForValidation is not executed, what do I miss?
My Model has this method:
public function update(Question $question)
{
$attr = request()->validate([
// some rules ( i know that i should move them to the other file, but it's not executed so it's here for now.
]);
$question->update($attr);
}
The FormRequest file-name is UpdateQuestionsRequest.php
The class is:
class UpdateQuestionsRequest extends FormRequest
{
public function rules()
{
return [
//
];
}
protected function prepareForValidation()
{
$this->merge([
'slug' => Str::slug($this->slug),
]);
dd($this); /////// never executed
}
}
The prepareForValidation method is not being executed because it is not being called in the update method. To use the UpdateQuestionsRequest class, it needs to be passed as a parameter to the update method. Here's an updated version of the update method:
public function update(UpdateQuestionsRequest $request, Question $question)
{
$attr = $request->validated();
$question->update($attr);
}
Note that the UpdateQuestionsRequest class is now being passed as the first parameter, and the $attr variable is being set to the validated data from the request. Also, the validated method is being used instead of validate to retrieve the validated data.
With this change, the prepareForValidation method should now be executed.