Posts Learn Components Snippets Categories Tags Tools About
/

How to cast datetime column to Carbon instance in Laravel

Learn how to cast datetime column to Carbon instance to get all of the helpful method in Laravel

Created on Aug 19, 2021

2063 views

To cast a datetime column to a Carbon instance, you can specify the column name on the protected $casts property from your model class. Imagine your model has a "published_at" column with a datetime type, you can cast it by defining it like below.
<?php

protected $casts = [
    'published_at' => 'datetime'
];
Once you have defined it, you will be able to call all of the Carbon helpful methods such as formatting the datetime value, adding, subtracting, getting human-readable value and etc.
<?php

$post = Post::first()->published_at;

dd($post->format('d M y')); // 26 Jun 21
dd($post->diffForHumans()); // 1 day ago 

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)