Laravel uses the Carbon date package by default, you can learn about that here: https://github.com/briannesbitt/Carbon
Any time you access a date property from a model you are automatically returned an instance of Carbon.
You can use the format method to specify a regular php date.
For example:
$user = User::find(1);
$date_string = $user->created_at->format('M j, Y'); /* returns something like March 11, 2014*/
If you have other date fields in your model, you can use attribute getters to change them to Carbon instances:
// the fieldname is arrival_date
public function getArrivalDateAttribute()
{
return Carbon::parse($this->attributes['arrival_date']);
}
You can then use format in your view:
$model->arrival_date->format('F j, Y');
Read more in the docs: http://laravel.com/docs/eloquent#accessors-and-mutators
@meigwilym , there's a better way to do that using date mutators, documented here, in the section right after the one you linked :)
@andrewsuzuki Wow - I hadn't read that section properly!
So just add my_date_field to the array in getDates()? Much simpler idea.
Off to do it right now!
Thanks,
Mei
So, if I use it in my view like so:
{{ $more_recent_updates->prod_update->format('M j, Y') }}
I get a fatal error exception and this "Call to a member function format() on a non-object".
What would cause that?
@jerauf See my previous post and look at date mutators in the docs. Your view code is correct, but you need to add prod_update to an array in the getDates method in your model, like so:
public function getDates()
{
/* substitute your list of fields you want to be auto-converted to timestamps here: */
return array('created_at', 'updated_at', 'deleted_at', 'prod_update');
}
Thank you. Sorry about that. I didn't quite understand. (This is my first Laravel site.)
I appreciate the help.
How can i set format with where()...?
$today = date( "Y-m-d H:i:s" );
$presentStudents = StudentAttendance::where( 'DATE_FORMAT(attendance_date,\'%Y-%m-%d\'', $today )
->get( [ 'student_id' ] )
->toArray();
and i want to use on just one place in my project...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community