Home > Net >  Undefined variable: request, error on laravel date validation
Undefined variable: request, error on laravel date validation

Time:11-26

in my laravel application I have a form for user registration

There I have an input field for user birthday .

From my controller, I'm validating the user inputs.

For the birthday user age has to be between 18-70.

For my user birthday, I have d/m/Y format for the front end but I'm converting it to Y-m-d format from my controller before saving it.

if(!empty($request->date_of_birth)){

                $date = str_replace('/', '-', $request->date_of_birth);
                $new_bday=date("Y-m-d", strtotime($date) );
                $request->merge(['date_of_birth' => ''.$new_bday.'']);    

            }

Now the issue is, every time when a user enters an invalid date (12/11/2021)it validates and display the old date(previously picked) in wrong format (2021-11-12)

To fix that I changed my date of birth validation to following in my controller

'date_of_birth'=>['required','bail','date_format:Y-m-d',function ($attribute, $value, $fail) {

                $age=Carbon::createFromFormat('Y-m-d', $value)->diff(Carbon::now())->y;
                if($age<18||$age>70){
                    $date = str_replace('-', '/', $value);
                    $new_bday=date("d/m/Y", strtotime($date) );
                    $request->merge(['date_of_birth' => ''.$new_bday.'']);
                    $fail('Âge invalide. l\'âge devrait être 18-70');
                }

            },]

but this kept giving me an error saying Undefined variable: request

CodePudding user response:

Try to access request like this \request() instead of $request.

\request() is a helper function that returns the same request object, which can be called anywhere from your application.

Also validating and submitting dates can cause some problems sometimes. I would suggest that you consider using some 3rd party tools like datetime picker, or flatpicker, for that purpose. It can be more user friendly, and you can assure that the dates entered in good format from the client side.

See:

getdatepicker.com/4

flatpickr.js.org/examples

  • Related