Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yossi's avatar
Level 2

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
    }
}
0 likes
5 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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.

yossi's avatar
Level 2

@LaryAI If anyone from laravel's team is reading - there is no way to know it from the documentations..

edit: oops, it is.

yossi's avatar
Level 2

@Snapey You are correct, I missed it (for some reason I assumed that the "calling" part is missing). thanks

Please or to participate in this conversation.