Laravel exists() Validation Example Tutorial

Laravel exists() Validation Example; In this tutorial, you will learn how to use exists validation in laravel application. More than the time we need to check is exiting the email or username in the database, so laravel provides us with exists() validation.

Exists validation rule in laravel check is records that are sent by the user is exists in the database table or not. The existing validation can be used in any database column such as checking email, username, etc.

The field under validation must exist in a given database table. If the column option is not specified, the field name will be used. This example shows you to validate email or username exists.

Solution 1: Exists Username Validation

$request->validate([
    'username' => 'required|exists:users,name',
]);

Solution 2: Laravel Exists Email

$request->validate([
    'email' => 'required|exists:users,email',
]);

Solution 3: exists Validation with Rule

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit them:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

$validator = Validator::make($request->all(), [
    'email' => [
        'required',
        Rule::exists('users')->where(function ($query) {
            $query->where('id', 1);
        }),
    ],
]);

I hope its works for you.

Leave a Comment