如何处理Laravel的日期输入 [英] How to handle date input in Laravel

查看:340
本文介绍了如何处理Laravel的日期输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个允许用户在表单中编辑几个日期的应用程序。日期以欧洲格式(DD-MM-YYYY)呈现,而数据库使用默认的YYYY-MM-DD格式。

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:


  • 使用帮助函数来转换保存前和检索后的日期(非常麻烦,需要很多代码)

  • 创建一个为每个日期属性分别设置属性,并使用 setNameAttribute getNameAttribute 方法进行解码/编码(同样麻烦和丑陋,需要额外的翻译/规则为每个属性)

  • 使用JavaScript转换加载和提交表单(不太可靠)的日期

  • 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?

推荐答案

在某些时候,您必须将日期从视图格式转换为数据库格式。正如你所说,有很多地方要做,基本上选择后端或前端。

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.

我在客户端进行转换(前端)使用javascript(您可以使用 http://momentjs.com 帮助此)。原因是您可能需要不同的格式,具体取决于客户端正在使用的区域设置(例如在浏览器中设置或在他的配置文件首选项中)。在前端进行格式转换可让您轻松转换成这些不同的日期格式。

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.

另一个优点是您可以使用在您的模型中保护$ date 属性,以便将Laravel句柄(获取和设置)自动为Carbon对象,而不需要执行此操作(请参阅 https://github.com/laravel/framework/blob/master/src/照亮/数据库/口述/ Model.php#L126 )。

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).

对于验证,您需要使用Laravel的内置验证规则,像这样:

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'

这篇关于如何处理Laravel的日期输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆