Posts Learn Components Snippets Categories Tags 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


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.

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.

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

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

Snippets by

PostSrc poster


Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets