Tryst with Laravel – Supercharging DateTime manipulation with Carbon
Tushar Bohra
January 19, 2018

Laravel has a beautiful support to include packages. This allows us to extend the functionalities of the framework to the project needs. With this we can easily have support of packages generic for PHP or specific to Laravel. One such PHP package that comes out of box with Laravel is Carbon. With Carbon we have a whole new dimension to interact with Dates.

 

The Carbon package is build by extending the PHP’s native DateTime¬†class. It provides a fluid way to interact, manipulate and work with date in PHP.

 

The results of an eloquent query that have a DateTime column are instances of the Carbon class by default. This makes it super convenient to directly utilise the functionality provided to work with date-time columns. It saves time and complexity in code by doing the instantiation of the class before hand.

 

So when we need to format the creation date of an result we can do-

Rather than-

 

There are many amazing tricks that Carbon offers in its package. It allows for fluently specifying the modification required in the date in a simple syntax-

 

These easy to use syntax and the fact that its available out the box on every query result make it an important concept that reduces the complexity of the code.