Laravel - Validation - required if the field is null

Let's say I have this HTML code:

<input type="email" name="email">
<input type="password" name="password">

Or that:

<input type="hidden" name="user_id" value="1">

(If the user is logged in, only the field will be displayed user_id. Else - credential fields).

When I create a request, there is a check that validates the user. if there is a field user_id(i.e. if it user_idexists in the user table), then there is no need to require emailand password. If not user_id, then the emailand fields will be required password.

In other words, I want to do something like this:

public function rules()
{
    return [
        'user_id'   => 'exists:users,id',
        'email'     => 'required_if_null:user_id|email|...',
        'password'  => 'required_if_null:user_id|...'
    ];
}
+4
source share
1 answer

Validation . , required_without:

public function rules()
{
    return [
        'user_id'       => 'exists:users,id',
        'email'         => 'required_without:user_id|email|unique:users,email',
        'password'      => 'required_without:user_id',
}
+4

Source: https://habr.com/ru/post/1650905/


All Articles