Laravel format time

Viewed 80

I have some problems with getting time on my app. I'm using laravel api to send informations to my React app. I have controller like:

public function index(){

        $user = auth()->user();
        $servers = Server::where('clientid', $user->id)
               ->orderBy('id', 'desc')
               ->take(10)
               ->get();

        if ($user) {
            $reposne['result'] = true;
            $reposne['servers'] = $servers;
        } else {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $reposne;
    }

And it's successfuly returns what I need, like:

{
    "result": true,
    "servers": [
        {
            "id": 2512,
            "clientid": 4,
            "boxid": 23,
            "ipid": 60,
            "vazido": 1584355476,
            "created_at": null,
            "updated_at": null,
            "status": "Active"
        }
    ]
}

But as you see there is column vazido that is actyally giving a timestamp. How can I make this time to actual human format?

3 Answers

By default, timestamps are formatted as 'Y-m-d H:i:s'.

I think your column type is int or string. So you can change the column type to timestamp or datetime.

$table->datetime('vazido')->change();

Or you can use mutator to convert the number to the datetime format, add this method to your Server Model:

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

You can add a $casts attribute in your Server Model and Laravel will handle the rest for you.

Sever Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Server extends Model
{
    protected $casts = [
        'vazido' => 'datetime:Y-m-d',
    ];
}

In your model, You can use Eloquent Mutators to formate the date as following.

public function getVazidoAttribute($value)
{
     return $value->format('Y-m-d');
} 
Related