Home > Software engineering >  1970-01-01 stores in the DB when a user tries to input a text in the date field in laravel without s
1970-01-01 stores in the DB when a user tries to input a text in the date field in laravel without s

Time:11-30

In my laravel application, I have a form to register new users.

In that form, I have a field to input user birthday.

Even though I'm taking user input dates in d/m/Y format, from my controller I'm converting them into Y-m-d before saving them to the DB.

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.'']);    

            }

I have the following validation rule for the birthday field.

'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 now the issue is,

If a user tries to enter a text (like test) rather than picking a date from the date picker and trying to submit the form, it validates and saves 1970-01-01 in the DB.

Use case- User types "Hello" in the birthday field and save the form. 1970-01-01 will be stored as the birthday

How can I display a proper validation message and avoid saving 1970-01-01 when a user tries to insert invalid input...

CodePudding user response:

Surely the better solution would be to not let them enter anything other than a date in the first place? At its simplest, using

<input type="date" required>

would force a date-format input on them, and disallow free input so that they cannot enter "test". Since that would result in a format that MySQL would accept (Y-m-d) then you don't have to do anything to the input in your controller.

CodePudding user response:

You are storing wrong date string, that's why getting 1970-01-01

dump/debug the date before storing.

The following code might solved your issue

if($request->date_of_birth) {
    $date = \Carbon\Carbon::createFromFormat('d/m/Y', $request->date_of_birth)->format('Y-m-d');

    $request->merge(['date_of_birth' => $date]);
}
  • Related