I've looked around, but haven't been able to find a clear way of returning Laravel timestamps / datetimes in a particular format. It doesn't really matter to me how it's saved in the database, but when I'm pulling the data, I'd like to format it so that it can be parsed by JavaScript. Does someone know of a good way that doesn't involve having to create multiple accessors?
Edit: To add more detail, I'm actually using AngularJS and would like the date returned in a format so that it can be understood by Angular and its date filter. With the current format, the date filter doesn't work because it can't parse the date, from what I can tell.
To define an accessor, create a getFooAttribute
method on your model where Foo is the "camel" cased name of the column you wish to access.
So, you should define an accessor for the test_date
(or anything else) attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of test_date
.
(In the example I'll define it in the User model)
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
protected $table = 'users';
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then you'll see the following format by default:
$user = User::find(1);
$user->test_date; //2015.11.12. 8:50:20
Let's define the DateTrait in App\DateTrait.php
file:
<?php
trait DateTrait {
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then use it every model where you'd like to format the test_date
column.
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
use App\DateTrait;
...
}
In your view just do something like this:
$variable->created_at->format('m-d-y')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With