doumen6605 2014-04-14 06:07
浏览 37

laravel 4.1更新失败的唯一验证

Laravel 4.1. I want to update a city, check the rules and it fails on unique check.

Rules:

public static $rules = [
    'name' => 'required|alpha_dash|unique:cities',
    'slug' => 'alpha_dash|unique:cities',
    'seo_title' => 'required|max:60|unique:cities',
    'seo_description' => 'required|max:160|unique:cities',
    'rank' => 'integer',
    'visible' => 'integer'
];

I know, I can smth like:

'name' => 'required|alpha_dash|unique:cities, name, ##',

where ## - id, but I cant dynamically set id to updated one.

'name' => "required|alpha_dash|unique:cities, name, $id", // doesnt work
'name' => "required|alpha_dash|unique:cities, name, $this->id", // doesnt work

Is there any way to do it normally ?

  • 写回答

3条回答 默认 最新

  • drgweamoi473182981 2014-04-14 06:29
    关注

    You can do it in separate ways.

    An easy way is to use different rules based on different actions . When you will create the model, you will use the rules that you currently have.

    When you will update the model, you will change the unique:cities to exists:cities

    I usually do this with a validation service.

    You create a base abstract Validator in services/ , which has a passes() function.

    For each model, you create a ModelValidator , in your case CityValidator. Where you put your rules like :

    public static $rules = [
        'new'=>[
        'name' => 'required|alpha_dash|unique:cities',
        'slug' => 'alpha_dash|unique:cities',
        'seo_title' => 'required|max:60|unique:cities',
        'seo_description' => 'required|max:160|unique:cities',
        'rank' => 'integer',
        'visible' => 'integer'],
    
        'edit'=>[
        'name' => 'required|alpha_dash|exists:cities',
        'slug' => 'alpha_dash|unique:cities',
        'seo_title' => 'required|max:60|exists:cities',
        'seo_description' => 'required|max:160|exists:cities',
        'rank' => 'integer',
        'visible' => 'integer'
        ]
    ];
    
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗