Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel date format in submission form (d-M-Y)

In the submit form in the blade template I have the following date form and it works fine with default date like Y-m-d.

But I want to show the date like d-M-Y, I have tried to find a usable solution with out luck

Here is the code that works with default date:

Here is the 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 Laravel versions from 4.2 and newer.

For Laravel 5.1 and newer, you will need to install it as a separate package as it's no longer part of the Laravel 5 core.

It was decided that the html/form builder are not a core requirement for the framework so it was removed from the core. The package I linked to is the one that was included with the L4 core and is being maintained as a separate package for L5 compatibility and usage, so you're safe using that if you choose to do so.

Thanks to @Bogdan for this update.

like image 631
Maytham Avatar asked Dec 02 '14 17:12

Maytham


1 Answers

If you need one date format for db storage and another for the user interaction, you need to process it before you display it and before you store it into the database. So you should do something like this:

1. Convert the date value for your form input:

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

2. Before saving convert it to the database required 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('Y-m-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 by Laravel.

like image 65
Bogdan Avatar answered Sep 28 '22 04:09

Bogdan