From your code it's unclear where $dateActive comes from, but it should be something like Carbon::create($old_date)->format('d/m/Y')
Converting Carbon instance to d/m/Y for form input (v4.2)
I am trying to add a date field to a form in Laravel 4.2. This field is saved as a property on the $companyBranch object which is then saved to a table in MySQL in the dateTime format.
$companyBranch->date_active
I have added:
protected $dates = ['date_active'];
to the model which is pulling the date from the database and converting to a Carbon object just fine. This is working perfectly in the view using:
{{ $companyBranch->date_active->format('d/m/Y')}}
However, in the create page, the $companyBranch is converted to an array to populate the form:
return View::make('company-branches.create', array(
'companyBranch' => $companyBranch->toArray()
));
In the form in edit mode, the input (text) field is populated with the raw string from the database:
2012-11-30 00:00:00
This is because the $companyBranch->date_active value is converted to carbon and then converted back to a string when the $companyBranch is sent to the View using:
'companyBranch' => $companyBranch->toArray()
This is the code for the form and it is utilising Form::model:
<div class="form-group">
{{ Form::label('date_active', 'Date Active', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
{{ Form::text( 'date_active', null, array('class' => 'form-control', 'placeholder' => 'DD/MM/YYYY')) }}
</div>
</div>
I have tried for hours to figure this out but I can't get a clear answer. I have tried adding:
protected $dateFormat = 'd/m/Y';
to the model but I think I have figured out that this is for Laravel 5 only.
Can anyone please help me convert the carbon instance to a formatted string BEFORE it is sent to an array and then to the form?
I saw another post in this forum by someone trying to solve the same problem and at the close of the thread, he stated the following:
"The difference was that Form:model() calls getAttributeValue() while otherwise toArray() is called.
Anyway, I solved the problem overriding Carbon's default date format:"
Carbon\Carbon::setToStringFormat('Y.m.d');
If this is the solution, where exactly can I do this?
Additionally, Ideally I would be able to use a Form::date input field to input the date in a dd/mm/yyyy format which would then convert to a timestamp for storage in the database.
Would I just be better of forgetting about storing as a date type and just store it as text??
Thanks a lot and apologies for my newbness.
@Jezzta667 why a DateTime? Do you need the microseconds?
All I need is the d/m/Y date but figured it would be good practice to store as a proper date format in order to use Carbon etc.
In that case definitely use a timestamp like I showed above, it will save you a lot of headaches.
Would I be better off just storing as plain text.
No. Use a timestamp.
Please or to participate in this conversation.