Reputation: 49
I am trying to edit the Migration in laravel so that the birth date gets the format needed. Now I have searched around on forums, and none get to my problem (that or I am stupid)
The format used in the code below does not seem to work, because I get errors on the dd part of the format. I've tried a couple of solutions, including editing the model to re-format the date, but that did nothing.
$table->date(dd, mm, YY)('birth_date');
Upvotes: 2
Views: 19318
Reputation: 41
When you set the dateFormat property, you are defining the format for how dates are stored in the database and how they are formatted when your model is serialized.
When you access your birthdate attribute on the model, you are still going to be given a carbon instance that can be used to format the birthdate in any way you would like.
Note that dateFormat will also change the format for your birth_date attributes.
Also Declare in the model:
class ModelName extends Model
{
protected $casts = [
'birth_date' => 'datetime:d/m/Y', // Change your format
];
}
Upvotes: 1
Reputation: 3712
$table->date('birth_date');
you can save data here format (Y-m-d) like (2019-12-31) Then when You get this you can show your desire format.
other way,If you think
$table->string('birth_date');
Then save data format (Y-m-d) like (2019-12-31).
When You try to show data your desire format just use Carbon\Carbon & format your date
Upvotes: 0
Reputation: 989
You should use this in your migration:
$table->date('birth_date');
Dates are always stored in the same format in the database. For example, the MySQL documentation on the DATE datatype says:
The supported range is '1000-01-01' to '9999-12-31'.
It is for your application to change the dates into a format you desire. There are different ways to achieve this. In your views you could use format()
:
{{ $user->birth_date->format('dd, mm, YY') }}
// or if birth_date can be NULL:
{{ optional($user->birth_date)->format('dd, mm, YY') }}
As an alternative, you could use an Accessor in your model:
public function getBirthDateAttribute($date)
{
if (is_null($date)) {
return null;
} else {
return Carbon::parse($date)->format('dd, mm, YY');
}
}
Upvotes: 4