How to handle date input in Laravel

27,848

Solution 1

At some point, you have to convert the date from the view format to the database format. As you mentioned, there are a number of places to do this, basically choosing between the back-end or the front-end.

I do the conversion at the client side (front-end) using javascript (you can use http://momentjs.com to help with this). The reason is that you may need different formats depending on the locale the client is using (set in the browser or in his profile preferences for example). Doing the format conversion in the front-end allows you to convert to these different date formats easily.

Another advantage is that you can then use the protected $dates property in your model to have Laravel handle (get and set) these dates automatically as a Carbon object, without the need for you to do this (see https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L126).

As for validation, you need can then use Laravel's built-in validation rules for dates, like this:

'date' => 'required|date|date_format:Y-n-j'

Solution 2

While client-side is good for UX, it doesn't let you be sure, all will be good.

At some point you will need server-side validation/convertion anyway.

But here's the thing, it's as easy as this:

// after making sure it's valid date in your format
// $dateInput = '21-02-2014'

$dateLocale = DateTime::createFromFormat('d-m-Y', $dateInput);

// or providing users timezone
$dateLocale = 
   DateTime::createFromFormat('d-m-Y', $dateInput, new DateTime('Europe/London'));

$dateToSave = $dateLocale
           // ->setTimeZone(new TimeZone('UTC'))   if necessary
           ->format('Y-m-d');

et voila!


Obviously, you can use brilliant Carbon to make it even easier:

$dateToSave = Carbon::createFromFormat('d-m-Y', $dateInput, 'Europe/London')
        ->tz('UTC')
        ->toDateString(); // '2014-02-21'

Validation

You say that Carbon throws exception if provided with wrong input. Of course, but here's what you need to validate the date:

'regex:/\d{1,2}-\d{1,2}-\d{4}/|date_format:d-m-Y'

// accepts 1-2-2014, 01-02-2014
// doesn't accept 01-02-14

This regex part is necessary, if you wish to make sure year part is 4digit, since PHP would consider date 01-02-14 valid, despite using Y format character (making year = 0014).

Solution 3

The best way I found is overriding the fromDateTime from Eloquent.

class ExtendedEloquent extends Eloquent {
    public function fromDateTime($value)
    {
        // If the value is in simple day, month, year format, we will format it using that setup.
        // To keep using Eloquent's original fromDateTime method, we'll convert the date to timestamp,
        // because Eloquent already handle timestamp.
        if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $value)) {
            $value = Carbon\Carbon::createFromFormat('d/m/Y', $value)
                ->startOfDay()
                ->getTimestamp();
        }

        return parent::fromDateTime($value);
    }
}

I'm new in PHP, so I don't know if it's the best approach. Hope it helps.

Edit:

Of course, remember to set all your dates properties in dates inside your model. eg:

protected $dates = array('IssueDate', 'SomeDate');
Share:
27,848
Arne
Author by

Arne

Updated on July 20, 2022

Comments

  • Arne
    Arne almost 2 years

    I'm working on an app that allows the user to edit several dates in a form. The dates are rendered in the European format (DD-MM-YYYY) while the databases uses the default YYYY-MM-DD format.

    There are several ways to encode/decode this data back and forth from the database to the user, but they all require a lot of code:

    • Use a helper function to convert the date before saving and after retrieving (very cumbersome, requires much code)
    • Create a separate attribute for each date attribute, and use the setNameAttribute and getNameAttribute methods to decode/encode (also cumbersome and ugly, requires extra translations/rules for each attribute)
    • Use JavaScript to convert the dates when loading and submitting the form (not very reliable)

    So what's the most efficient way to store, retrieve and validate dates and times from the user?

  • M165437
    M165437 over 8 years
    "You should use either date or date_format when validating a field, not both." – Laravel Docs