Laravel Magazine
Carbon Date Handling Tips for Laravel Developers
Featured

Carbon Date Handling Tips for Laravel Developers

Carbon is bundled with every Laravel app, and Eloquent automatically casts your created_at and updated_at columns to Carbon instances. Most developers use maybe ten percent of what it offers. These tips cover the parts that save real time and prevent real bugs. Cast Your Own Columns to Carbon Eloquent only auto-casts timestamps unless you tell it otherwise. Add your date columns to the casts() method so they come back as Carbon instances instead of raw strings: protected function casts(): array { return [ 'published_at' => 'datetime', 'trial_ends_at' => 'datetime', 'birth_date' => 'date', ]; } Now $post->published_at->diffForHumans() just works, instead of giving you a Call to a member function on string error. Use Human-Readable Comparisons Carbon's named comparison methods read like English and avoid timezone mistakes: $post->published_at->isPast(); $subscription->trial_ends_at->isFuture(); $event->starts_at->isToday(); $invoice->due_date->isBetween(now(), now()->addDays(7)); Store U...

Latest News

More Articles

Latest Links

Stay Updated

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.