简体   繁体   English

Laravel 5-FormRequest规则中的条件语句

[英]Laravel 5 - Conditional statements within FormRequest rules

Using Laravel 5.0, within a form request, validation rules can be made as such: 使用Laravel 5.0,在表单请求中,可以这样制定验证规则:

class MyCustomRequest extends Request {
    public function authorize()
    {
        return Auth::check();
    }


    public function rules()
    {
        $rules = [
            'title' => 'required|max:255',
        ];

        return $rules;
    }
}

How do I create a rule that tests a conditional statement such as: 如何创建测试条件语句的规则,例如:

'user_id' === \Auth::id();

where user_id is an item from the requests parameter bag 其中user_id是来自请求参数包的项

You can use exists rule in your rule array. 您可以在规则数组中使用存在规则。

https://laravel.com/docs/5.2/validation#rule-exists https://laravel.com/docs/5.2/validation#rule-exists

public function rules()
{
    $rules = [
        'title' => 'required|max:255',
        'user' => 'exists:users',
    ];

    return $rules;
}

Edit: If you trying to check if a submitted value matches with your values you can use the rule "in". 编辑:如果您尝试检查提交的值是否与您的值匹配,则可以使用规则“中”。

https://laravel.com/docs/5.2/validation#rule-in https://laravel.com/docs/5.2/validation#rule-in

You need to provide ids in a comma separated string. 您需要以逗号分隔的字符串形式提供ID。 Not tested but you can try something like this. 未经测试,但是您可以尝试类似的方法。

public function rules()
{
    $ids = implode(",", DB::table('users')->all()->pluck('id'));
    $rules = [
        'user_id' => 'in:'. $ids,
    ];

    return $rules;
}

If you just trying to check with current user id then this should work. 如果您只是尝试使用当前用户ID进行检查,则应该可以使用。

public function rules()
{
    $rules = [
        'user_id' => 'in:'. Auth::user()->id,
    ];

    return $rules;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM