Support the ongoing development of Laravel.io →
Database Blade
Last updated 2 years ago.
0

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*/
Last updated 2 years ago.
0

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

Last updated 2 years ago.
0

@meigwilym , there's a better way to do that using date mutators, documented here, in the section right after the one you linked :)

http://laravel.com/docs/eloquent#date-mutators

Last updated 2 years ago.
0

@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

Last updated 2 years ago.
0

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?

Last updated 2 years ago.
0

@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');
}
Last updated 2 years ago.
0

Thank you. Sorry about that. I didn't quite understand. (This is my first Laravel site.)

I appreciate the help.

Last updated 2 years ago.
0

No problem, glad to help!

Last updated 2 years ago.
0

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...

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

jerauf jerauf Joined 16 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.