dongweihuai5601 2018-10-27 07:06
浏览 249

Laravel 5使用不同日期格式的唯一(数据库)验证

I'm using laravel 5.5 with MySQL database.

Here is my current code:

private function setValidationRule(Request $request,$actionCode) {
    $rules = [];
    $rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';
    return $rules;
}

public function postCreate(Request $request) {
    //Previous code...

    $validator = \Validator::make($request->all(),
        $this->setValidationRule($request,$actionCode),
        $this->setCustomValidationRuleMsg($request,$actionCode)
    );
    $validator->setAttributeNames($this->setValidationAttributeNames());
    if ($validator->fails()) {
        $view = $viewPri->withErrors($validator)->withInput();
    } else {
        $view = $viewSec;
    }
    return $view;
}

The posting data from client is DD-MM-YYYY = '15-10-2018'.

Then i want to validate the date uniqueness with the rule :
$rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';

Yes the validation is true (success) but the laravel generated sql was wrong to get the uniqueness :
select count(*) as aggregate from empofday where odaydate = '15-10-2018'
so the resulting sql would be 0 instead of 1.

But if i try manual sql with the following code :
select count(*) as aggregate from empofday where odaydate = '2018-10-01'
resulting value 1.

So, my question is how to set date format for laravel validating uniqueness on database to use d-m-Y format instead of Y-m-d?

Thanks for the help.

  • 写回答

1条回答 默认 最新

  • dqnrk44682 2018-10-27 11:33
    关注

    If you are using simple text box for date input, I recommend to change that to some date picker plugin, the plugins do have functionality to have a date format that is displayed different than what is sent back to the database.

    After that you can remove the date format validation, because it will be managed by the plugin, and unique will run because the format sent by the plugin can be set to be in MySQL format (YYYY-MM-DD)

    For jQuery UI Date picker http://api.jqueryui.com/datepicker/#option-altFormat

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序