Convert timestamp to date in Laravel?

timestamp columns like created_at are being parsed first. the U is simply the timestamp format. you can return your own format. for other formats see date docs.

edit: as stated in my comment, getDateFormat() is for both ways (insert, selects). your best bet would be using format inside the model. example:

public function getMyBirthdayAttribute()
{
    return $this->my_birthday->format('d.m.Y');
}

use $model->my_birthday to call the attribute.

// controller
$posts = Post::all();

// within sometemplate.blade.php
@foreach($posts as $post)
    my formatted date: {{ $post->my_birthday }}
@endforeach

The better way to manage dates with Laravel IMHO is to use the getDates accessor that is build into Laravel.

All you need to do is to set a method on your Model as such.

public function getDates()
{
    return [
        'my_birthday',
        'created_at',
        'updated_at',
    ];
}

This will return a Carbon object. Carbon is insanely awesome for manipulating dates.

It is what Laravel does by default to created_at and updated_at.

You can then do things like:

$my_birthday->diffForHumans()  // 2 Days ago
$my_birthday->format('d.m.Y')  // 20.02.1979

There are tons of helpers here for you. Check out the Carbon docs: https://github.com/briannesbitt/Carbon

Definitely worth learning. It might not be easy to understand for a beginner. However, I would advise you take a look and get your head around it. It will change your life - Dates can be a pain!


In this case, you need to convert the date within the query, if mysql is being used as your database then you may use a raw query like this:

// Assumed my_birthday is like 1255033470
$raw = DB::raw("date_format(from_unixtime(my_birthday),'%b %d, %Y %l:%i %p') as dob");
$result = Model::get(array('id', 'username', $raw));

You may write it within single line:

$result = Model::get(array('id', 'username', DB::raw("...")));