Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Carbon Dates

I'm really trying to get a grasp on Carbon and how to handle dates with it. Inside my database I have a published_at field that displays the datetime of when an article is posted.

Example: 2014-04-21 15:36:40

I am wanting to format it in my table so that when it displays it will do so in the way that appears as such: April 21, 2014.

Do I need to run a function over the object property in my view to accomplish this?

0 likes
13 replies
i960's avatar

In your model you need to tell Laravel to convert that field to a Carbon object. It does this automatically for created_at and updated_at. So you would add this to your model:

    protected $dates = ['published_at'];

Then you can run normal carbon functions on it, either in your view, or as an accessor in your model. Something like this:

    public function getPublishedAtAttribute($value)
    {
        return $value->diffForHumans(); // Use whatever you want here to format the date, this is just an example
    }

Then in your view you would do something like this:

{{ $article->published_at }}

And it will automatically be formatted instead of cluttering up your views. Of course, I'm going completely off of memory here and I haven't tested any of this, but the general idea should work.

jrdavidson's avatar

With the following I am receiving this error:

Call to a member function toFormattedDateString() on string

I'm trying to get it formatted so it is April 21, 2014.

<?php

class NewsArticle extends \Eloquent {

    protected $fillable = [];

    protected $dates = ['published_at'];

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'news_articles';

    public function category()
    {
        return $this->belongsTo('NewsCategory', 'news_category_id');
    }

    public function author()
    {
        return $this->belongsTo('User', 'author_id');
    }

    public function setPublishedAtAttribute($date)
    {
        $this->attributes['published_at'] = Carbon::parse('Y-m-d', $date);
    }

    public function getPublishedAtAttribute($date)
    {
        return $date->toFormattedDateString(); // Use whatever you want here to format the date, this is just an example
    }
}
<tbody>
        @foreach ($newsArticles as $article)
            <tr>
                <td>{{ $article->id }}</td>
                <td>{{ $article->title }}</td>
                <td>{{ $article->category->name }}</td>
                <td>{{ $article->author->name }}</td>
                <td>{{ $article->published_at }}</td>
                <td>Action Buttons Here</td>
            </tr>
        @endforeach
    </tbody>
i960's avatar

Hmm, maybe it's not converting it to Carbon. Try this maybe?

    public function getPublishedAtAttribute($date)
    {
        return $this->asDateTime($date)->toFormattedDateString();
    }
RachidLaasri's avatar
public function getPublishedAtAttribute($date)
{
    return Carbon::parse($date)->toFormattedDateString();
}
JarekTkaczyk's avatar

@xtremer360 You definitely don't want that set mutator:

    public function setPublishedAtAttribute($date)
    {
        $this->attributes['published_at'] = Carbon::parse('Y-m-d', $date);
    }

This is storing a Carbon object in your attributes, while you want a datetime string there.

With this mutator you have inconsistency:

$news = new NewsArticle;
$news->published_at = '2015-02-05';
$news->published_at; // Feb 5, 2015

// but
$news = NewsArticle::first();
$news->published_at; // error that you just pasted above

You need Carbon object only when you are accessing the date property, not when you are setting it.

Now, what you might want is not using mutators at all, just $dates = ['published_at'];. Then whenever you retrieve the published_at you get it as a nice Carbon object, that you can use however you need in given case. Like:

$news1->published_at->diffForHumans($news2->published_at); // 5 days after

$news1->published_at->toFormattedDateString(); // Feb 5, 2015

$news1->published_at->diffForHumans(); // 2 days ago

This gives you more flexibility than using accessor, that enforces string value, which is what you are trying now. I suggest using Presenter that wraps your model and does it, if you really want to avoid calling $news->published_at->toFormattedDateString() eg. in your view.

1 like
crispy's avatar

It would be nice if Laravel would detect date fields from the DB schema and convert them to Carbon dates automatically, rather than having to specify what fields are "dates" in a class property. Any reason that shouldn't be a feature?

bobbybouwmann's avatar

@crispy You don't always want to have a Carbon instance when you work with dates, that's the reason ;)

1 like
khaledSMQ's avatar

you can try this it's work for me just overide

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
{

//.....
    public function getDates()
    {
        return array('created_at', 'updated_at', 'deleted_at', 'first_login');
    }
}

Please or to participate in this conversation.