Laravel date format in submit form (dMY)

In the submit form in the blade template, I have the following date form, and it works fine with the default date, for example Ymd .

But I want to show the date as dMY , I tried to find a useful solution with luck

Here is the code that works with the default value:

Here is a model

 public static $rules = [ 'birthday' => 'date' ]; protected $fillable = ['birthday']; 

Here is the controller method

 public function update($id) { $kid = Kid::findOrFail($id); $validator = Validator::make($data = Input::all(), Kid::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $kid->update($data); return Redirect::to('kids/list'); } 

Here is the Blade template

 {{ Form::model($kid, ['method' => 'PATCH', 'route' => ['kids.update', $kid->id], 'files' => true], ['class' => 'form-horizontal']) }} {{ Form::text('birthday', null, ['class' => 'form-control']) }} {{ Form::submit('Confirm update', ['class' => 'btn btn-primary']) }} {{ Form::close() }} 

UPDATE

This works for all versions of Laravel from 4.2 and later.

For Laravel 5.1 and later, you will need to install it as a separate separate package , since it is no longer part of the Laravel 5 kernel.

It was decided that the html / form builder was not a basic requirement for the framework, so it was removed from the kernel. The package I'm attached to includes the one that was included in the L4 kernel and is supported as a separate package for compatibility and use of L5, so you can safely use this if you want to do this.

Thanks @Bogdan for this update.

+7
date laravel laravel-5 laravel-4
source share
1 answer

If you need one date format for the db repository, and another for user interaction, you need to process it before displaying it and before saving it to the database. Therefore, you should do something like this:

1. Convert the date value for form input:

 {{ Form::text('birthday', date('dM-Y', strtotime($kid->birthday)), ['class' => 'form-control']) }} 

2. Before saving, convert it to the required database format:

 public function update($id) { $kid = Kid::findOrFail($id); // Convert birthday format to be compatible with database ISO 8601 format $data = Input::all(); $data['birthday'] = date('Ym-d', strtotime($data['birthday'])); $validator = Validator::make($data, Kid::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $kid->update($data); return Redirect::to('kids/list'); } 

If you want a more object oriented way of handling dates, you can use Carbon , which is already included with Laravel.

+11
source share

All Articles