Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

torkil's avatar

Inconsistencies in date casting?

Just wondering about your opinions on this:

When working with dates and using the new eloquent date casting in Laravel 5.6, I came across this, which I found weird.

1. Inconsistent with other cast functionality

First of all, there is the inconsistency with other $casts, where date casting only works when doing toArray or toJson:

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
        'created_at' => 'datetime:Y-m-d H:00'
    ];
}

$user->is_admin; // is cast to boolean
$user->created_at; // not cast to string, still a Carbon instance

This is by design by the looks of it, but inconsistent all the same.

2. Inconsistency between only and toArray

Both $user->only() and $user->toArray() will return arrays. But only toArray will cast the date to a string:

$attributes = $user->toArray();
$attributes['created_at']; // cast to string
$attributes['is_admin']; // cast to boolean

$attributes = $user->only(['is_admin', 'created_at']);
$attributes['created_at']; // still a Carbon instance!
$attributes['is_admin']; // cast to boolean

What do you think? IMO $user->only() is synonymous with casting to array and filtering, so I expected it to behave similarly with $user->toArray().

0 likes
5 replies
biishmar's avatar

Check this one throughly, https://laravel.com/docs/5.6/collections#method-only

it returns collection, in collection created_at stills in carbon instance

$attributes = $user->only(['is_admin', 'created_at'])->toArray();
$attributes['created_at']; // now its string!
$attributes['is_admin']; // cast to boolean
torkil's avatar

@biishmar You are confusing collection->only() with model->only(). They are two different functions. The latter returns an array and is defined in HasAttributes.php.

biishmar's avatar
$attributes = $user->only(['is_admin', 'created_at']);

Would you tell me what user variable contains? i need to see that line also....

if you dont want carbon instance anywhere..use this below line in model.

protected $timestamp = false;
Snapey's avatar

@biishmar

protected $timestamp = false; tells eloquent that your table does not contain created_at and updated_at columns, so don't go trying to update them.

It does not alter the casting of dates. This is the $dates property.

Please or to participate in this conversation.