【问题标题】:Laravel 6 - validate unique, ignore on two conditions - same user and name. Also $this->id is null on updateLaravel 6 - 验证唯一,忽略两个条件 - 相同的用户和名称。更新时 $this->id 也为空
【发布时间】:2019-12-11 13:44:02
【问题描述】:

到目前为止,我有以下规则。

$rules['name'] = [
    'required',
    'string',
    'min:3',
    'max:255',
    Rule::unique('user_templates', 'name')->ignore($this->id),
];

用户可以创建记录,但他的所有记录必须有一个唯一的名称(其他用户可以有相同名称的记录)。我怎样才能做到这一点?此外,$this->id on update 始终为空。我究竟做错了什么?

控制器

public function update(UserTemplatesRequest $request, $slug)
{
    try {
        $model = UserTemplates::where('slug', XSS::clean($slug))
            ->firstOrFail();
    } catch (ModelNotFoundException $err) {
        return redirect()->action('UserTemplatesController@index');
    }

    $data = $request->validated();

    if ($model->updateTemplate(XSS::clean($data, ['file']), $request)) {
        $message = "There was an error, please try again";
        $action = 'index';
        $id = '';
    } else {
        $message = "Category Updated";
        $action = 'edit';
        $id = $model->id;
    }

    return redirect()->action("CategoriesController@{$action}", [$id])
        ->with('message', $message);
}

【问题讨论】:

    标签: laravel laravel-6 laravel-validation


    【解决方案1】:

    根据您的规则,您可以尝试使用 where 子句将其缩小到一个用户而不是整个项目,例如:

          Rule::unique('user_templates', 'name')->where(function (Builder $query) {
                return $query->where(
                    'user_id', '=', $this->user()->id;
            })
    

    user_id 是您的user_templates 表中的列,它与您的用户表一起用作外键。

    关于$this->id 应该是$this->user()->id 来检索你的用户ID

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2018-10-26
      • 2017-03-26
      • 2016-08-03
      • 2016-03-11
      • 2021-02-07
      相关资源
      最近更新 更多