Search code examples
phplaravellaravel-validationlaravel-request

Laravel validation require if the user is logged in


So let's say I've got a custom request called CreateReviewRequest.

In this request, I've got this method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name'      => 'required_if(auth->logged)',
        'comments'  => 'required|max:255',
        'stars'     => 'required|min:1|max:5',
    ];
}

As you can see in the name key, I want from the client to be required to fill the name field if he's not logged in.

So my question is, how can I exactly require my client to fill the name when he's a guest?


Solution

  • You can use check() method:

    public function rules()
    {
        return [
            'name'      => auth()->check() ? 'required' : '',
            'comments'  => 'required|max:255',
            'stars'     => 'required|min:1|max:5',
        ];
    }