Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Validation - Require if field is null

Let's say I have this html code:

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

Or this:

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

(If the user is logged in, only the user_id field will be shown. else - the credentials fields).

When I create a request, there's a validation that checks the user. if the field user_id exists (i.e if user_id exists in the users table), then there's no need to require email and password inputs. If there's no user_id, then the email and password fields will be required.

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|...'
    ];
}
like image 527
Eliya Cohen Avatar asked Aug 11 '16 10:08

Eliya Cohen


1 Answers

After reading the Validation docs again, I found a solution. I just needed to do the opposite, using the required_without validation:

public function rules()
{
    return [
        'user_id'       => 'exists:users,id',
        'email'         => 'required_without:user_id|email|unique:users,email',
        'password'      => 'required_without:user_id',
}
like image 136
Eliya Cohen Avatar answered Oct 21 '22 03:10

Eliya Cohen