panthro
panthro

Reputation: 24061

Add Data If Validator Fails in Form Request

I've checked the docs and SO but when I do the following I get the error Maximum execution time of 30 seconds exceeded.

In my custom form request I have:

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($validator->fails()) {
            session()->flash('type', 'xyz');
        }
    });
}

As soon as I removed the if statement the max execution error goes away.

How can I add some data to session if validation fails?

Upvotes: 0

Views: 649

Answers (4)

Donkarnash
Donkarnash

Reputation: 12835

If you want to add some data when the validation fails using after validation hook, you can try to check if the error bag has any messages and if it has then flash the requisite data to session


    public function withValidator($validator)
    {
        $validator->after(function($validator) {
            if($validator->errors()->count('messages')) {
                session()->flash('type', 'xyz');
            }
        });
    }

Upvotes: 1

Abilogos
Abilogos

Reputation: 5030

because what has mentioned in Doc was:

call any of its methods before the validation rules are actually evaluated

your code going through an infinite loop by recursive calling himself on calling $validator->fails()

Upvotes: 1

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

As said in laravel doc

withValidator allows you to call any of its methods before the validation rules are actually evaluated

So, you cannot call fails() method inside withValidator method. Because it performs validation and cannot be called in a method that adds a rule that is ought to perform before validation.

You should define a validator as said here in your controller, then call fails() method on it.

$validator = Validator::make(...);

if ($validator->fails()) {
    session()->flash('type', 'xyz');
}

Upvotes: 1

ml59
ml59

Reputation: 1641

The reason is because you are calling fail in the after callaback and this is doing an infinite recursive call. Let me explain:
if you dig in the source code here is the fails implementation:

public function fails()
    {
        return ! $this->passes();
    }

Here is our interesting part of the passes() method:

 public function passes()
    {
       //.....
       //once the validation fails call the callback
        foreach ($this->after as $after) {
            $after();
        }
    
        return $this->messages->isEmpty();
    }

So if in the after() callback you are calling the fail() method then the fail() method will call the after() callabck etc.

Upvotes: 1

Related Questions