Hello I have laravel project that store data created_at as a timestamp, I would call it from database, but it still show timestamp format, how can I convert it to date format without changing my column type? image
here is my model:
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->timestamp;
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->timestamp;
}
and how should I call it in view or .blade file?? Thank you
CodePudding user response:
To convert to human readable string try changing your functions as below:
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->toFormattedDateString();
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->toFormattedDateString();
}
toFormattedDateString()
function will convert to format like Jun 22, 2020
. See this article for more alternatives https://www.leonelngande.com/format-dates-for-humans-with-carbon-in-php/.
To use in blade file simply access the parameter like:
$modelvariablename->created_at
CodePudding user response:
In your model:
public function getCreatedAtAttribute(): Carbon {
return Carbon::parse($this->created_at);
}
public function getUpdatedAtAttribute(): Carbon {
return Carbon::parse($this->created_at);
}
For use:
$model->created_at->format('d.m.Y');
CodePudding user response:
If you pass the data from controller to blade You can call in your blade file like this ...
<sapn>{{ $variable->updated_at->toDateString() }}</span>
Or
<span>{{ $variable->updated_at->format('Y-m-d') }}</span>
if you want to convert to inside controller .
public function getCreatedAtAttribute($value)
{
return $value->toDateString();
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return $value->toDateString();
}
Or you can try carbon
use Carbon\Carbon;
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}