Book Image

Laravel 5 Essentials

By : Martin Bean
Book Image

Laravel 5 Essentials

By: Martin Bean

Overview of this book

Table of Contents (15 chapters)
Laravel 5 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Easier date and time handling with Carbon


Laravel bundles Carbon (https://github.com/briannesbitt/Carbon), which extends and augments PHP's native DateTime object with more expressive methods. Laravel uses it mainly to provide more expressive methods on the date and time properties (created_at, updated_at, and deleted_at) of an Eloquent object. However, since the library is already there, it would be a shame not to use it elsewhere in the code of your application.

Instantiating Carbon objects

Carbon objects are meant to be instantiated like normal DateTime objects. They do, however, support a handful of more expressive methods:

  • Carbon objects can be instantiated using the default constructor that will use the current date and time as follows:

    • $now = new Carbon();

  • They can be instantiated using the current date and time in a given timezone as follows:

    • $jetzt = new Carbon('Europe/Berlin');

  • They can be instantiated using expressive methods as follows:

    • $yesterday = Carbon::yesterday();

    • $demain = Carbon::tomorrow('Europe/Paris');

  • They can be instantiated using exact parameters as follows:

    • Carbon::createFromDate($year, $month, $day, $tz);

    • Carbon::createFromTime($hour, $minute, $second, $tz);

    • Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

Outputting user-friendly timestamps

We can generate human-readable, relative timestamps such as 5 minutes ago, last week, or in a year with the diffForHumans() method as follows:

$post = App\Post::find(123);
echo $post->created_at->diffForHumans(); 

Boolean methods

Carbon also provides a handful of simple and expressive methods that will come in handy in your controllers and views:

  • $date->isWeekday();

  • $date->isWeekend();

  • $date->isYesterday();

  • $date->isToday();

  • $date->isTomorrow();

  • $date->isFuture();

  • $date->isPast();

  • $date->isLeapYear();

Carbon for Eloquent DateTime properties

To be able to call Carbon's methods on attributes stored as DATE or DATETIME types in the database, you need to list them in a $dates property in the model:

class Post extends Model {
  // ...
  protected $dates = [
    'published_at',
    'deleted_at',
  ];
}

You don't need to include created_at or updated_at, as these are automatically treated as dates.