Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undefined variable: request, error on laravel date validation

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading