Home > Blockchain >  laravel how to return unix-timestamps format in number/string format?
laravel how to return unix-timestamps format in number/string format?

Time:10-11

Iam using Laravel 8

i made all steps to change table->timestamp() to unix-timstamp but its return in '2022-10-10T21:09:28.000000Z'

in Model.php

class Post extends Model
{
    HasFactory;
    protected $dateFormat = 'U';
}

in create_post_table.php

$table->unsignedInteger('created_at');
$table->unsignedInteger('updated_at');

result in data base:

enter image description here

return response()->json result:

enter image description here

i need to return in '1665434137' format ??

CodePudding user response:

found answer in this question

in modal.php add

protected $casts = [
    'created_at' => 'timestamp',
    'updated_at' => 'timestamp'
];

CodePudding user response:

Hi please follow these steps :

in your migration file ,change the

$table->unsignedInteger('created_at');
$table->unsignedInteger('updated_at');

to

$table->timestamps();

it will automatically create two columns in your table

Also please drop $casts and $dataFormat in your model.php file ,you don't need them anymore .

Finaly to achieve your result it is enough to do this :

Model->created_at->timestamp
Model->updated_at->timestamp

Notice the Model in above code should be replaced with the model object you have , for example :

Post::find(1)->created_at->timestamp

or any other method of post object .

  • Related