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

bljdavidson's avatar

array_diff with Laravel's new date serialization with ->toArray()

Hi all!

So I am attempting to compare two arrays with array_diff(). However, since Laravel 7, when using toArray(), Laravel uses a new date serialization method which always returns with the dates. Whereas previously they wouldn't.

With the new date serialization:

// Expected
Array (
    'before' => Array (
        'title' => 'Eaque aperiam vel rerum disti...borum.'
    )
    'after' => Array (
        'title' => 'changed'
    )
)

// Actual
Array (
    'before' => Array (
        'title' => 'Eaque aperiam vel rerum disti...borum.'
        'updated_at' => '2020-10-24T22:23:45.000000Z'
        'created_at' => '2020-10-24T22:23:45.000000Z'
    )
    'after' => Array (
        'title' => 'changed'
        'updated_at' => '2020-10-24T22:23:45.000000Z'
        'created_at' => '2020-10-24T22:23:45.000000Z'
    )
)

With the old way:

// Expected
Array (
    'before' => Array (
        'title' => 'Eaque aperiam vel rerum disti...borum.'
    )
    'after' => Array (
        'title' => 'changed'
    )
)

// Actual
Array (
    'before' => Array (
        'title' => 'Eaque aperiam vel rerum disti...borum.'
    )
    'after' => Array (
        'title' => 'changed'
    )
)

I understand I can revert back to the older way as suggested in the docs, which does fix the issue:

use DateTimeInterface;

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}

However, I would like to know if we can achieve the expected result without reformatting the dates back to the previous way?

Thanks!

Ben

0 likes
3 replies
Snapey's avatar

The only difference is that the dates are now in ISO format (with milliseconds). This change should not affect whether your array has timestamps or not?

Are you sure previously you had not added the dates to the $hidden array?

bljdavidson's avatar

Hi @snapey!

Thanks for getting back to me. I didn't even know about the $hidden array, so I've not used that.

When I add the code to revert back to the previous format, it works as expected.

A bit of context. I am saving the current state of the database field to a variable $old = [], and then comparing the updated state with the $old.

array_diff($this->old, $this->toArray());

Thanks!

Ben

Please or to participate in this conversation.