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

gcbenlloch's avatar

Date format changing between query and eloquent

I cant figure out how to get the timestamps formated the same running eloquent and with a query

$query = DB::table('libros');

if ($request->user()->isTutor()) {
     $query->where('desactivado', false);
}

$libros = $query->get();

// "created_at":"2021-03-24 14:03:19","updated_at":"2021-03-24 14:03:19"
$libros = Libro::all();

// "created_at":"2021-03-24T13:04:57(dot)000000Z","updated_at":"2021-03-24T13:04:57(dot)000000Z"

I will like to always get the date formated like this 2021-03-24 08:13:38

0 likes
5 replies
tykus's avatar

By default, the timestamps are cast as Carbon instances on the Eloquent Model, so the string stored in the database is parsed as a Carbon instance when you use the Eloquent Builder - because the results all are Libro model instances:

$libros = Libro::all();

The Carbon instance is cast / serialized as a 2021-03-24T13:04:57.000000Z because it

When you drop down to the Query Builder DB::table('libros') you get none of the casting, relationships, behaviours that Eloquent provides - you get a stdClass object with raw (string) data.

I will like to always get the date formated like this 2021-03-24 08:13:38

You can format a Carbon instance however you please using the underlying date formatters:

@foreach($libros as $libro)
	{{ $libro->created_at->toDateTimeString() }}
@endforeach
gcbenlloch's avatar

Thanks!

I managed to get it working using mutators

Heres the code in case someone else is in the same situation

    public function getCreatedAtAttribute($date)
    {
        return Carbon::parse($date)->timezone(date_default_timezone_get())->format('Y-m-d H:i:s');
    }

    public function getUpdatedAtAttribute($date)
    {
        return Carbon::parse($date)->timezone(date_default_timezone_get())->format('Y-m-d H:i:s');
    }
tykus's avatar
tykus
Best Answer
Level 104

Why do you need an accessor; you have broken the created_at and updated_at as far as being Carbon instances now!

Know that you have the ability to override how dates are serialized on the model itself:

https://laravel.com/docs/8.x/eloquent-serialization#date-serialization

protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}

You could set this as the default behaviour in a base model if needed.

gcbenlloch's avatar

I dind't know about that method.

Thanks a lot for the help!

Please or to participate in this conversation.