简体   繁体   中英

Laravel 5 - Conditional statements within FormRequest rules

Using Laravel 5.0, within a form request, validation rules can be made as such:

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

You can use exists rule in your rule array.

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

You need to provide ids in a comma separated string. 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.

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

    return $rules;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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