Search code examples
laravelunix-timestamp

Get Unix timestamp in laravel


I am storing created_at and updated_at as unix timestamp

for that i add following line to my modal its working fine.

class Test extends Model
{
    protected $dateFormat = 'U';

    protected $fillable = [
        'user_id','question_id','answer',
    ];
}

but problem is when i retrieve record its give me readable format instead of unix timestamp so how i get value as store in database i.e(1593624368). in database i use int(11) data-type for created_at and updated_at

created_at: 2020-07-01T17:45:03.000000Z,
updated_at: 2020-07-02T08:53:14.000000Z,

Solution

  • U can use Laravel Date Casting

    For your case:

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp',
    ];