Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danyal14's avatar

Validation with Rules::exists

When validating post data, I would like to use Laravel validation to check if email exists in users table along with other validations, questions is can Rule::exists() be used to fulfill this purpose?

        $validator = Validator::make($request->all(), [
            'username' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::exists('users')->where(function ($query, $request) {
                    $query->where('email', $request->usename);
                })
            ], 'email',
            'password' => 'required|string|min:6',
        ]);
0 likes
3 replies
takdw's avatar
takdw
Best Answer
Level 11

I believe there is a built in Laravel modifier you can use. The exists rule.

$validator = Validator::make($request->all(), [
            'username' => [
                'required',
                'string',
                'email',
                'max:255',
                'exists:users,email' // check that the value exists in the 'email' field of the 'users' table
            ], 'email',
            'password' => 'required|string|min:6',
        ]);

And also, I don't really know the benefit of using Validator::make() but I just validate the request object itself. Like this:

// You can also do this on a $request (\Illuminate\Http\Request) object
request()->validate([
            'username' => 'required|email|max:255|exists:users,email',
            'password' => 'required|string|min:6'
        ]);
3 likes
danyal14's avatar

@TAKDW - @takdw Thanks for the reply, it works.

reason I am using Validator::make() to capture validation errors in variable and then to wrap in response as I want.

Like $validator = Validator::make() and response

{
    "status": "fail",
    "message": "Validation errors.",
    "errors": {
        "username": [
            "The selected username is invalid."
        ],
        "old_password": [
            "The old password field is required."
        ]
    }
}

And request()->validate() & response

{
    "errors": {
        "username": [
            "The selected username is invalid."
        ],
        "old_password": [
            "The old password field is required."
        ]
    }
}

Just to make response as unified as possible.

1 like
takdw's avatar

@danyal14 Thank you for clearing that up for me. I have always wondered but never really dug deep to see the differences. This will definitely come in handy.

Please or to participate in this conversation.