0

I am trying to set the date format as (d-m-Y), but error message says as stated below:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '20-03-2020'

Below is my Controller validation code

   $request->validate([

       'date' => 'required|date_format:d-m-Y',    
   ]);

I also tried to set the format in my model, which was also futile

protected $dateFormat = 'd-m-Y';

How can I set the date_format?

5
  • @TsaiKoga can't it be set to 'm-d-Y' Commented Mar 20, 2020 at 7:57
  • @TsaiKoga, i got this message The date does not match the format d-m-Y Commented Mar 20, 2020 at 8:02
  • yes, i am getting "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value" Commented Mar 20, 2020 at 8:12
  • 2
    MySQL's default date format is Y-m-d, you try to add d-m-Y, that's what this error is trying to tell you. Change the format back to Y-m-d when you insert data in your database Commented Mar 20, 2020 at 8:25
  • I have check the source code, DateTime::createFromFormat('!d-m-Y', "20-03-2020")->format('d-m-Y') == "20-03-2020"; return true. So the validation is passed. I think kerbholz is right. You need to post your table column's type. Commented Mar 20, 2020 at 8:31

1 Answer 1

1

According to the documentation, setting $dateFormat on your model "determines how date attributes are stored in the database." Setting it to a value that conflicts with your database's date format will of course lead to the SQL errors you're seeing. So leave it alone.

Adding the property to the $dates array will ensure it's automatically converted to a Carbon object when set, and correctly formatted when saved:

protected $dates = ['myproperty'];

This works transparently because Carbon accepts d-m-Y as a format for creating objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.