vendredi 16 novembre 2018

How to set an existing property as a date property in Laravel?

I have fields start_date and end_date on one of my models.

For some time, we have been saving these properties as Carbon dates without using the $dates property:

start_date: {
    date: "2016-09-28 00:00:00.000000",
    timezone_type: NumberLong("1"),
    timezone: "-04:00"
},
end_date: {
    date: "2016-09-30 00:00:00.000000",
    timezone_type: NumberLong("1"),
    timezone: "-04:00"
}

I would like to make use of the $dates property in Laravel and convert them to Carbon dates.

However, Laravel doesn't appreciate when I simply add them to the property:

protected $dates = ['start_date', 'end_date'];

And then try to convert them:

foreach($models as $model) {
    $model->start_date = new Carbon($model->start_date);
    $model->end_date = new Carbon($model->end_date);
    $model->save();
}

As it errors out on the Accesssor:

exception: "ErrorException"
file: "/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php"
line: 760
message: "preg_match() expects parameter 2 to be string, array given"

Any thoughts?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire