Reputation: 433
I want to use the Carbon on Views I'm including it on the top of the views file but it doesnt work, I'm doing it like this.
<?php use carbon/carbon;?>
@extends('main_layout')
@foreach ($myquery as $mytask)
<tr>
<td >
{{($mytask->firstname)}}
</td>
<td >
{{($mytask->lastname)}}
</td>
<td>
{{($mytask->logon)}}
</td>
@section('content')
@stop
I just get errors. I want to convert the {{($mytask->logon)}} to human readable format using carbon
Upvotes: 20
Views: 50748
Reputation: 16344
EDIT 2021-10-29
It appears that Laravel now encourages the use of date casts for this question:
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'created_at' => 'datetime:Y-m-d',
];
Original Answer
I would add sommething quoting Laravel Documentation for googlers to add how you can transform your SQL datetime fields into Carbon objects:
In your Model:
protected $dates = ['created_at', 'updated_at', 'disabled_at','mydate'];
All the fields present on this array will be automatically accessible in your views with Carbon functions like:
{{ $article->mydate->diffForHumans() }}
Upvotes: 37
Reputation: 31
Just Copy Paste it into your Model
public function getCreatedAtAttribute($value)
{
$date = new Carbon($value);
return $date->toDayDateTimeString();
}
And called ->created_at
like you normally called in your view.
Don't forget to use the Carbon Class Model
Upvotes: 3
Reputation: 5025
Blade Use:
{{ \Carbon\Carbon::parse($mytask->logon)->diffForHumans() }}
Output: For a task that is one day ago from now
1 day ago
More for Human readable time by Carbon you can read - Carbon Difference For Humans
Upvotes: 14
Reputation: 2520
You need not add a use statement for carbon in the view. Just make sure that $mytask->logon
is indeed a carbon object and use the format()
method to turn it into a string
{{ $mytask->logon->format('Y/m/d') }}
Edit:
If $mytask->logon
is a carbon object use:
{{ $mytask->logon->diffForHumans() }}
If it's still a string use:
{{ \Carbon\Carbon::createFromTimeStamp(strtotime($mytask->logon))->diffForHumans() }}
I would advise to do that in the controller though or a view composer to keep your view neat.
Upvotes: 18
Reputation: 3790
For laravel 5 Note if you need to do some custom mutations, chuck this in your model.
/**
* The string attribute that should be cast to custom carbon date.
*
* @var array
*/
public function getTimeAttribute()
{
return Carbon::createFromTimestampUTC($this->attributes['time']/1000);
}
Dont worry you can still access the original attribute.
New = {{ $event->time }} Original = {{ $event->getOriginal('time')}}
Hope this helps someone who cannot use the standard way mentioned.
Upvotes: 1