mySQL DATE format is Y-m-d
For localization reasons, users submit date fields to my Laravel 5.4 application in the d-m-Y
form, which are saved to a detenutodal
field in mySQL.
I used mutators to convert the two formats, in my Attore
model, like this.
<?php
namespace App;
//use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Attore extends Model
{
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
'detenutodal'
];
/**
* detenutodal: DB Y-m-d => m-d-Y
*
* @param date $value
* @return date
*/
public function getDetenutodalAttribute($value)
{
return Carbon::parse($value)->format('d-m-Y');
}
/**
* detenutodal: m-d-Y => DB Y-m-d
*
* @param date $value
* @return date
*/
public function setDetenutodalAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}
}
as you may see, the detenutodal
attribute is added to the $dates
to make it into a Carbon
instance (not declaring it seems to make no difference. Actually I was unable to have detenutodal
behave like a Carbon instance, and I had to explicitly call Carbon::parse
)
I create a new Attore
model in AttoreController
like this:
$this->validate(request(), [
'detenutodal' =>'nullable|date_format:"d-m-Y"',
]);
Attore::create(request()->all());
The detenutodal field is correctly validated, and I am sure the mutator is called as I dd
'ed its invocation. the correct detenutodal
value is passed to it - e.g. 30-06-1943
and it returns 1943-06-30
.
but the create
fails with this error:
SQLSTATE[HY000]: General error: 1364 Field 'detenutodal' doesn't have a default value (SQL: insert into `attores` (`nome`, `enteopersona`, `paternita`, `maternita`, `annonascita`, `luogonascita`, `residenza`, `professione`, `gradoistruzione`, `updated_at`, `created_at`) values (Aminto Pestalozzi, persona, Agenore Pestalozzi, Giacinta Tortelazzi, 1910, Caorso in Strà ' lva', Via Morigi 4, Caorso, Bracciante, Scuola professionale, 2017-05-18 14:23:22, 2017-05-18 14:23:22))
As you may see, mySQL complains that detenutodal
has no default value as detenutodal
has completely disappeared from the query, while I would expect that the mutator correctly updated the field before the invocation of Attore::create
and added it to the query.
Can anyone shed some light?
Thanks