skip to Main Content

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 ??

2

Answers


  1. Chosen as BEST ANSWER

    found answer in this question

    in modal.php add

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

  2. 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 .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search