Forcing Laravel to Treat a Database Column as a Date

Database Eloquent Views

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at March 9, 2016 2:43 pm

Laravel will automatically treat user-defined timestamps as dates however there is an easy fix

On a recent project we wanted to track user's subscription renewal dates within the users table, and so defined a TIMESTAMP column named subscription_renews_at. This works as one would expect in terms of assignment:

$today = new \Carbon\Carbon;
$user->subscription_renews_at = $today->addYear()->toDateTimeString();

However, when retrieving subscription_renews_at, Laravel will treat the value as a string, meaning you can't do cool things like this in your view:

{{ $user->subscription_renews_at->format('F d, Y') }}

This forces you to instead use awkward workarounds like this:

{{ date('F d, Y', strtotime($user->subscription_renews_at)) }}

The fix is easy though. Open the User model and add the following class property:

protected $dates = [

With this property defined, Laravel will begin treating subscription_renews_at as a date, allowing you to use format().