ventures 999
ventures 999

Reputation: 199

Laravel Create Date return different format

I tried to select the create_data from the database, the date format in the database is like "2021-05-18 11:06:01", but when I retrieve and display it, it's will show the format like is "2021-05-18T03:06:01.000000Z". Does anyone know why will become like that? I want the date which is actually like the database store which is "2021-05-18 11:06:01". However, the create_date inside DB the format is UTC +8, but when receive it will show UTC format.

enter image description here

Data return

[0] => Array (
    [id] => 1
    [log_name] => login
    [description] => login
    [subject_type] => App\Models\Users
    [subject_id] => 0
    [causer_type] => App\Models\User
    [causer_id] => 2
    [properties] => ""         
    [created_at] => 2021-05-18T03:06:01.000000Z
);

Code

$lastLoggedActivity = ActivityLog::where('causer_id', $userid)
    ->orWhereIn('subject_id', $selectparentid)
    ->with('getLogType')
    ->with('getCauserDetails')
    ->orderBy('created_at', 'desc')
    ->get()
    ->toArray();

Upvotes: 1

Views: 13108

Answers (4)

Lawrence Macharia
Lawrence Macharia

Reputation: 119

I had to use mutators just like @yudiz-solutions above but could not achieve exactly what I wanted until I added timezone value:

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

OR

public function getCreatedAtAttribute($value)
{
    return Carbon::parse($value)->timezone('Africa/Nairobi')->toDateTimeString();
}

NB: Documentation recommends use of UTC timezone:

Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript.

Upvotes: 2

Yudiz Solutions
Yudiz Solutions

Reputation: 4459

In ActivityLog model add this,

use Carbon\Carbon;

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

Upvotes: 7

jrcamatog
jrcamatog

Reputation: 1484

Add a serializeDate method to your model to change it's format on responses.

/**
 * 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');
}

Upvotes: 4

Chinh Nguyen
Chinh Nguyen

Reputation: 1266

because laravel auto cast created_at and updated_at, you can readmore at this and to change created_at add to model:

protected $casts = [
    'created_at' => 'datetime:Y-m-d H:i:s',
];

Upvotes: 1

Related Questions