【问题标题】:Laravel validation array, access to element on validation?Laravel验证数组,访问验证元素?
【发布时间】:2018-08-29 05:45:09
【问题描述】:

我有一个要验证的元素数组,这个数组有这种形式

{
    "slugs" : {
        1 : "prueba",
        2 : "test"
}

Slugs 是输入 <input name="slugs[{{ $lang->id }}]">,数字是语言的 ID 1 = spanish / 2 = english

我想要的是在这样的表单请求中验证这些字段的唯一性

public function rules()
{
    $rules = [
        //
        'slugs.*' => Rule::unique('translation_entries')->where(function($query) {
            //here i want to access the * that represent the lang id
            //like this $query->where('lang_id','=',$query->*);
        })
    ];
}

我可以访问唯一 Rule 类中的索引 * 吗?

【问题讨论】:

  • 你使用的是什么版本的 Laravel?

标签: laravel laravel-validation


【解决方案1】:

只要你使用 Laravel >=5.5,你就可以使用closure

'slugs.*' => [
    function ($attribute, $value, $fail) {
        $id = str_after($attribute, '.');

        if (\DB::table('translation_entries')->where('lang_id', $id)->where('slug', $value)->exists()) {
            $fail('The slug has already been taken.');
        }
    },
],

'slug' 更改为translation_entries 表中列的名称(如果不同)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 2016-09-01
    • 2018-04-13
    • 2019-02-21
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    相关资源
    最近更新 更多