Carbon Helper

A quick helper function for Carbon dates

Image By Curtis MacNewton on Unsplash

Posted on

I use the nesbot/carbon class in my projects nearly 100% of the time. It offers some incredible functionality for handling and formatting dates. If you've not used it, I highly recommend checking it out.

One thing that gets tiring though is having use Carbon\Carbon at the top of all my PHP files and having to write out Carbon::parse() any time I want to use the package. Instead, I like to use a little helper function that I include in my applications:

if ( ! function_exists('carbon') )
{
    function carbon($date)
    {
        return \Carbon\Carbon::parse($date);
    }
}

Now, instead of this:

use Carbon\Carbon;
// ...
$date = Carbon::parse('tomorrow');

You can do this:

$date = carbon('tomorrow');

Much more simple and clean.

Newsletter


Get notified when I post something new.

Latest Quick Tips


Bash Alias for Creating a Laravel Project
  • A Quick Tip posted on 2018-07-31
Carbon Helper
  • A Quick Tip posted on 2017-10-05

Latest Blog Posts


Custom Tinkerwell Integration
  • A Blog Post posted on 2019-11-05
How to Persist Databases Across Homestead Instances
  • A Blog Post posted on 2018-02-16
How to Set Up Xdebug on Laravel Homestead and VSCode
  • A Blog Post posted on 2017-10-23
Compiling LESS Using Blade Templates
  • A Blog Post posted on 2016-07-21