6
votes

I want to get UNIX timestamp or convert created_at or updated_at date to UNIX timestamp format from database fields (created_at and updated_at) in laravel 5.8 , how can i do this?

this is my code in my controller :

public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}

and in view/archives.blade.php :

<?php echo $data;?>

the result is :

{“created_at”:”2019-03-17 19:10:30″}

but i want the result be like this :

{“created_at”:”1552849830″}

how can get this result?

3

3 Answers

2
votes
$string = '2019-03-17 19:10:30';

$obj = new stdClass;
$obj->created_at = $string;

$collection = [$obj];

foreach ($collection as $k => &$v) {
    $collection[$k]->created_at = strtotime($v->created_at);
}

//var_dump($collection);

or

$string = '2019-03-17 19:10:30';

$obj = new stdClass;
$obj->created_at = $string;

$collection = [$obj];

array_walk($collection, function (&$item, $key) {
    $item->created_at = strtotime($item->created_at);
});

//var_dump($collection);

Or in your case

    public function viewArchives()
    {
        $data = Archive::select('created_at')->get();
        foreach ($data as $k => &$v) {
            $v->created_at = strtotime($v->created_at);
        }
        return view('view.archives', compact('data'));
    }

or

    public function viewArchives()
    {
        $data = Archive::select('created_at')->get();
        array_walk($data, function (&$item, $key) {
            $item->created_at = strtotime($item->created_at);
        });
        return view('view.archives', compact('data'));
    }

This is good place to use array_walk() function.

0
votes

Add strtotime() view/archives.blade.php :

<?php echo strtotime( $data );?>
0
votes

With an Eloquent Model one can actually define the $casts per column:

class SomeModel extends Model
{

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'datetime'
    ];
}

If you want epoch timestamps instead, just remove this cast (which is likely present).


When the timestamp isn't from any Eloquent Model, one still can render it with Blade:

@php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
@endphp

Or the other way around:

@php
echo strtotime( $isodate );
@endphp