laravel how to validate as equal to a variable

K1-Aria picture K1-Aria · Aug 18, 2017 · Viewed 23.7k times · Source

in laravel validation (registering) i want to compare one of the fields with a php variable (it should be equal with that)

how can i do this?

protected function validator(array $data)
{

    return Validator::make($data, [
        'name' => 'required|max:255',
        'phone' => 'required|min:10|max:11|unique:users',
        'email' => 'required|email|max:255',
        'password' => 'required',
        'password_confirmation' => 'required',
        'user_captcha' => 'required'
    ]);
}

Answer

Leonardo Cabré picture Leonardo Cabré · Aug 18, 2017

You can do it for example for name field like this:

$variable = "something"
return Validator::make($data, [
    'name' => [
        'required',
        Rule::in([$variable]),
    ],
    'phone' => 'required|min:10|max:11|unique:users',
    'email' => 'required|email|max:255',
    'password' => 'required',
    'password_confirmation' => 'required',
    'user_captcha' => 'required'
]);

Remember to import Rule Class (use Illuminate\Validation\Rule;)

You can get more info in: https://laravel.com/docs/5.4/validation#rule-in

EDIT

As suggested by @patricus, you can also concatenate the variable

$variable = "something"
return Validator::make($data, [
    'name' => 'required|in:'.$variable,
    'phone' => 'required|min:10|max:11|unique:users',
    'email' => 'required|email|max:255',
    'password' => 'required',
    'password_confirmation' => 'required',
    'user_captcha' => 'required'
]);