Home > database >  Invalid datetime format: 1292 Incorrect date value: '2 August, 2022' LARAVEL
Invalid datetime format: 1292 Incorrect date value: '2 August, 2022' LARAVEL

Time:08-22

I can not insert date in my project. Can anyone please review my codes to find the error?

in my table--

public function up()
    {
        Schema::create('basic_infos', function (Blueprint $table) {
            $table->id('EmpID');
            $table->string('Emp_Name');
            $table->date('DOB')//date of birth;
            $table->timestamps();
        });
    }

in my blade file--

<input type="date" name="DOB"  id="date_of_birth"  data-bs-toggle="tooltip" title="Date of Birth">

in my controller--

 public function store(Request $request)
    {
        $basicInfo = BasicInfo::create([
            'Emp_name' => $request->Emp_name,
            'DOB' => $request->DOB,
        ]);
    }

when I click the save button, then the error SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '2 August, 2022' for column.. shows. How do I solve this

CodePudding user response:

use a mutator in your model BasicInfo.The error thrown because MySQL DOB column type date expects 'Y-m-d' format.

protected function dob(): Attribute
{
    return Attribute::make(
        set: fn($value) => Carbon::createFromFormat('d M, Y', $value),
    );
}

CodePudding user response:

You need to parse the date from format that your frontend is sending.

This will work in your case:

$dob = \Carbon\Carbon::parse($request->DOB);

If you want to be more strict, validate format on the request first, eg. inline:

$request->validate([
  'DOB' => 'date_format:j m, Y'
]);

More on validation: https://laravel.com/docs/9.x/validation#rule-date-format

  • Related