验证特定规则-Laravel [英] Validate specific rule - Laravel

查看:89
本文介绍了验证特定规则-Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新的Laravel版本.

I am using latest Laravel version.

我有requests/StoreUser.php:

public function rules() {
    return [
        'name' => 'required||max:255|min:2',
        'email' => 'required|unique:users|email',
        'password' => 'required|max:255|min:6|confirmed'
    ];
}

用于创建用户.

现在我需要并更新用户,但是如何仅执行特定规则?

Now I need and to update the user, but how can I execute only specific rules ?

例如,如果未提供name,而仅提供了email,那么如何仅对电子邮件运行验证?

For the example, if name is not provided, but only the email, how can I run the validation only for the email ?

推荐答案

这比您想象的要容易.使规则取决于HTTP方法.这是我的工作示例.

This is easier than you thought. Make rules depend on the HTTP method. Here is my working example.

public function rules() {
    // rules for updating record
    if ($this->method() == 'PATCH') {
        return [
            'name' => 'nullable||max:255|min:2', // either nullable or remove this line is ok
            'email' => 'required|unique:users|email',
        ];
    } else {
    // rules for creating record
        return [
            'name' => 'required||max:255|min:2',
            'email' => 'required|unique:users|email',
            'password' => 'required|max:255|min:6|confirmed'
        ];
    }

}

这篇关于验证特定规则-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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