I have Laravel. I have a form. I have a MySQL database. There are some dates in it. When I bind the model and the form, the form is dutifully populated with raw MySQL dates. This is obviously not what I need.
My question is: How do I get a model bound form to display dates in a more readable way?!? There is not chance to intercept and format the data. Or maybe for a more general solution, is there any way to do some proessing on any data between the model and the form, before the user sees it?
Am I thinking of this all wrong? A billion thanks!
You may add an accessor method in your model like this:
public function getCreatedAtAttribute($date)
{
$date = new \Carbon\Carbon($date);
// Now modify and return the date
}
This will be called for created_at
. Also check date-mutators if you need to override defaults. Check Carbon Docs.
You can format the date in the form using the format()
method.
If you're using it in a form element:
{{ Form::text('name', $model->created_at->format('d/m/Y H:i')) }}
If you're displaying it as plain text:
{{ $model->created_at->format('d/m/Y H:i') }}
If you would like the user to be able to modify the date in a nice way, you could use three different select fields. Here's an excerpt from a project I worked on that allows the user to change the date of birth:
<div class="form-group {{ $errors->has('date_of_birth') ? 'has-error' : '' }}">
{{ Form::label('date_of_birth', 'Date of Birth', ['class' => 'control-label']) }}
<div class="form-inline">
{{ Form::selectRange('date_of_birth[day]', 1, 31, null, ['class' => 'form-control']) }}
{{ Form::selectMonth('date_of_birth[month]', null, ['class' => 'form-control']) }}
{{ Form::selectYear('date_of_birth[year]', date('Y') - 3, date('Y') - 16, null, ['class' => 'form-control']) }}
</div>
{{ $errors->first('date_of_birth', '<span class="help-block">:message</span>') }}
</div>
This is contained within a form that has the model bound to it.
Side Note
The alternative answer posted in here actually overrides the default way that laravel handles dates, and unless you actually return a carbon object, you'll never have the luxury of using the format
method, or any of the other handy things that carbon has.
If you have other columns that contain dates, add them to the data mutators list:
public function getDates()
{
return ['created_at', 'updated_at', 'date_of_birth', 'some_date_column'];
}
This will now make it so that each of those is an instance of Carbon
allowing you to format as you please, whenever you please and easily modify, duplicate and a whole host of other things. For more information regarding this, see: http://laravel.com/docs/eloquent#date-mutators
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