javascriptphpjsonlaravellaravel-5.7

Laravel - POST date as JSON and save as DATE Constraint in MySQL


Problem Statement:

I've defined DATE format in MySQL Column DataType Constraint database.

However, While sending Date in JSON object in ISO format where it must be DATE DataType in MySQL Constraint using Laravel Mass Assignment and all input data

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '1990-01-01T00:00:00.000Z' for column 'date_of_birth' at row 1


Files & Configuration:

Blade file

<input type="date" id="date_of_birth">

<script> 
    var dob = new Date( $("#date_of_birth").val() ).toISOString();
</script>

Post JSON object

{
    date_of_birth: "1990-01-01T00:00:00.000Z"
}

Setting attribute for Mass Assignment

App\Models\User.php

protected $fillable = [ 'date_of_birth' ]

App\Http\Controllers\UpdateController.php

    public function update(Request $request, User $user)
    {

        $id = $user->updateOrCreate($request->all());

Solution

  • I would like to give credit @Armagen. Using mutator.

    use Carbon\Carbon;
    
    class User extends Model
    {
        /**
         * Set the user's date_of_birth.
         *
         * @param  string  $value
         * @return void
         */
        public function setDateOfBirthAttribute($value)
        {
            $this->attributes['date_of_birth'] = Carbon::parse($value);
        }
    }