在Laravel 5中进行编辑时表单请求中的唯一字段 [英] Unique fields in form requests when editing in Laravel 5

查看:53
本文介绍了在Laravel 5中进行编辑时表单请求中的唯一字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Laravel表单请求中实施唯一字段的最佳方法,但编辑时除外.最明显的例子是只允许一次使用电子邮件地址,即系统中的每个用户都需要一个唯一的电子邮件地址.

I'm looking for the best way to enforce unique fields in Laravel form requests, except for when editing. The most obvious example would be only allowing an email address to be used once i.e. each user in a system would need a unique email address.

这是通过使字段唯一而实现的使用表单请求的直接方法:

This is straight-forward to achieve using form requests, by making the field unique:

public function rules()
{
    return [
        'email' => ['required', 'email', 'unique:users,email'],
    ];
}

这将使该字段为必填字段,可作为电子邮件验证并在用户表中使其唯一.非常适合创建新用户.但是编辑呢?用户想要编辑其个人资料并再次保存相同的电子邮件地址是完全合理的(完全有效).但是,当然会触发 unique 规则,因为该电子邮件已经在使用中"(尽管用户试图对其进行编辑).

This makes the field required, validates as an email and makes it unique in the user's table. Perfect for creating a new user. But what about editing? It's totally plausible for a user to want to edit their profile and save the same email address again (which is totally valid). But, of course, the unique rule will fire because the email is already "in use" (albeit by the user trying to edit themselves).

Laravel通过传递 user 表的ID来忽略此问题,从而提供了一种解决方法:

Laravel offers a way around this, by passing in the ID of the user table to ignore:

'email' => ['required', 'email', 'unique:users,email,'.$userId]

但是如何获取用户ID?也许这是一个不好的例子,因为获取登录的用户ID很简单,但是未存储在会话中的其他对象呢?

But how to get the user ID? Maybe this is a bad example because it's trivial to get the logged in user ID, but what about other objects that aren't stored in the session?

如果使用的是REST,则该对象的ID将在URL中,并且可以通过以下路线使用:

If one is using REST, then the ID of the object would be in the URL and available using the route:

$userId = $this->route('order');

但这似乎很脏.在不使用REST修改对象的其他情况下又如何呢?在Laravel 5中编辑对象时,你们如何在表单请求中实施唯一性?

But this seems very dirty. And what about other instances where you're not using REST to modify an object? How do you guys enforce uniqueness in form requests when editing objects in Laravel 5?

推荐答案

如果需要,您可以有2个具有不同规则的表单请求.我认为从FormRequest中获取信息来调整规则并不无济于事,因为FormRequest是一个Request,并且您可能需要一些信息来决定如何进行验证或授权.

You can have 2 form requests with different rules if you want. I don't think it is dirty to pull information from the FormRequest to adjust the rules as the FormRequest is a Request and you may need some of that information to decide how to do the validation or authorization.

我有一篇关于使用FormRequest进行创建和更新的帖子,该规则使用规则中的唯一规则,该规则使用route参数附加到唯一规则. asklagbox-博客-用于存储和更新的表单请求

I have a post about using a FormRequest for create and update, using a unique rule in the rules, that uses a route parameter to append to the unique rule. asklagbox - blog - Form Request for Store and Update

因为它使用HTTP方法来知道它是用于存储还是更新,并且如果正在发生更新,则追加到唯一规则(Rest).如果您不使用REST,您仍然可以执行此操作,则只需检查HTTP方法之外的其他内容,以了解这是用于存储还是更新.如果需要,您可以调整此方法以检查输入值,而不是用于附加到唯一规则的路由参数.由于FormRequest是特定于资源的,因此您实际上并不需要发疯,不必想想您想做的每一种其他可能的方式,否则您的应用程序/API可能会开始变得不一致.

In that it uses the HTTP method to know if it is for store or update and appends to the unique rule if it is an update happening (Rest). If you weren't using REST you could still do this you would just need to check something besides the HTTP Method to know if this is for store or update. You could adjust this method to check an input value instead of a route parameter for appending to the unique rule if you wanted as well. Since the FormRequest is pretty specific to the resource you don't really need to go crazy and think of every single possible other way you want to do something, or your app/API could start to become inconsistent.

// added to base FormRequest

protected $updateMethods = ['PUT', 'PATCH'];

protected function appendUnique($key, $keyName = 'id')
{
    if (in_array($this->method(), $this->updateMethods) && $param = $this->route($key)) {
        if ($param instanceof Model) {
            $rt = "{$param->getKey()},{$param->getKeyName()}";
        } else {
            $rt = "{$param},{$keyName}";
        }
        return ','. $rt;
    }
}

然后,FormRequest的rules方法中的数组将具有以下内容:

Then the array in the rules method of your FormRequest would have something like this:

'email' => 'required|unique:users,email'. $this->appendUnique('user'),

我经常使用路由模型绑定(隐式和显式),这就是为什么这样设置,并且很少让我检查的资源通过输入而不是路由参数传递.

I use Route Model Bindings (implicit and explicit) often which is why this is setup like this and rarely would have the resource I am checking against be passed via an input and not a route parameter.

我希望这会有所帮助.

这篇关于在Laravel 5中进行编辑时表单请求中的唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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