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-

$result = Model::find(1);
return $result->created_at->toFormattedDateString();

Rather than-

$result = Model::find(1);
$created_at = new DateTime($result->created_at);
return $created_at->format('<some format>');

 

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-

$result = Model::find(1);
return $result->created_at->addDays(60)->endOfWeek()->toFormattedDateString();

 

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.