Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andersonmichel's avatar

Error Saving Date format (d/m/Y) to (Y-m-d)

The problem is that laravel is trading the day for the month before saving the record.

That way, the date 05/10/2018 is saved on database as 2018-05-10, and the date 10/05/2018 is saved as 2018-10-05.

So if I put in the field a day greater than 12 some kind of error occurs and the record is saved as 1970-01-01.

I'd like to know why this is happening and what to do to fix it. Thank you.

0 likes
6 replies
Cronix's avatar

It's happening because you're not converting it into the date format the database requires. You need to convert it to yyyy-mm-dd before saving.

You can do it manually or using a mutator which will convert automatically when saving: https://laravel.com/docs/5.7/eloquent-mutators

To do it manually, you'd have to create a date using that format.

$date = '10/15/2005'; // Oct 15, 2005
$converted = Carbon\Carbon::createFromFormat('m/d/Y', $date);
echo $converted->toDateString(); // 2005-10-15
knubbe82's avatar

Carbon\Carbon::parse('string')->format('Y/m/d')

andersonmichel's avatar

My model extends a base model with a setAttribute method that converts to the right formating...

So.. this is not a converting issue... because the date is changed to {Y-m-d} correctly... It is saved in database with the correct year... but unfortainly day and month invested.

andersonmichel's avatar

public function setAttribute($key, $value){

    if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/", $value)) 

    {

        $this->attributes[$key] = substr($value, 6, 4).'-'.substr($value, 3, 2).'-'.substr($value, 0, 2); 

    }

}

gorakhyadav's avatar

Try something like this.

   Date::make('Birthday')->resolveUsing(function ($date) {                
   return $date->format('Y-m-d');
  }),
gorakhyadav's avatar

You can also use Add the $casts in the model, so you will solve the problem.

  protected $casts =[
  'birthday'=> 'date:Y-m-d'
  ];

Please or to participate in this conversation.