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

631 views Asked by At

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());
2

There are 2 answers

0
Maqsud On BEST ANSWER

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);
    }
}
0
Stefan Krüger s-light On

based on the tip to use Mutators from @Armagen -
for dates there is this simplified magic Date Mutators:
App\Models\User.php

class User extends Model
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'date_of_birth',
    ];
}

you just have to add your attribute to this list and Laravel does the Carbon thing for you. :-)