Home / Snippets / How to cast datetime column to Carbon instance in Laravel
How to cast datetime column to Carbon instance in Laravel cover

How to cast datetime column to Carbon instance in Laravel

4K

3 years ago

0 comments

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 
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this