Sunday, March 19, 2017

Inserting user provided dates before 1970 to MySql using Laravel and Carbon

I'm using the following code:

$birthday = request('birthday_day') . "-" . request('birthday_month') . "-" . request('birthday_year');
    $birthday = Carbon::createFromFormat('d-m-Y', $birthday);
    $min_year = date('Y') - 10;

    if ($birthday->gte(Carbon::create($min_year, 1, 1))) {
        return back()->withErrors(['message' => 'You need to be at least 10 years old to sign up.'])->withInput();
    }

    $user = User::create([
        'first_name' => request('first_name'),
        'last_name' => request('last_name'),
        'email' => request('email'),
        'password' => bcrypt(request('password')),
        'birthday' => $birthday, //THE PROBLEM
        'gender' => request('gender'),
        'verified' => 0,
        'verification_code' => bcrypt(str_random(30) . request('email'))
    ]);

I get the following error message when I run it:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1943-01-17 08:45:49' for column 'birthday' at row 1 (SQL: insert into `users` (`first_name`, `last_name`, `email`, `password`, `birthday`, `gender`, `verified`, `verification_code`, `updated_at`, `created_at`) values (Name, name2, example@example.com, $2y$10$qOMKZBGF4rsyEtkH2Cd5CuPDshwN7ULEKWfakrvDTrIo5KQTWTO.i, 1943-01-17 08:45:49, male, 0, $2y$10$oU88Yddwug6dgapv./REJ.NTWlCHKMXOUHVyOGd2UJXCqvHpIIW3y, 2017-03-19 08:45:49, 2017-03-19 08:45:49))

This happens only for the dates with years lesser than 1970. I read about how this happens because of unix and mysql timestamps, but can't seem to fix this.



via Mav

Advertisement