📌  相关文章
📜  $validator = Validator::make($request->all(), [ - PHP (1)

📅  最后修改于: 2023-12-03 14:38:44.187000             🧑  作者: Mango

Validator::make() - Laravel Validation

Validator::make() is a validation method offered by the Laravel framework. This method allows developers to create new Validator instances that can validate requests and data inputs. The $request->all() parameter represents the input data to be validated, and the second parameter is an array of validation rules.

Usage

Here is an example on how to use Validator::make():

$validator = Validator::make($request->all(), [
    'username' => 'required|max:255',
    'email' => 'required|email|unique:users|max:255',
    'password' => 'required|min:8|max:255',
]);

In this example, the method validates three input parameters: username, email, and password. The validation rules check if these parameters are required, if the email is valid and unique in the users table, and if the password is at least 8 characters long.

Validation with custom error messages

Developers can attach custom error messages to their validation rules. Here is an example:

$validator = Validator::make($request->all(), [
    'email' => 'required|email|unique:users|max:255',
], [
    'required' => 'The :attribute field is required.',
    'email' => 'The :attribute must be a valid email address.',
    'unique' => 'The :attribute is already in use.',
]);

In this example, custom error messages are provided for the required, email, and unique rules.

Markdown formatted code snippet
$validator = Validator::make($request->all(), [
    'username' => 'required|max:255',
    'email' => 'required|email|unique:users|max:255',
    'password' => 'required|min:8|max:255',
]);

// Attach custom error messages
$validator->setAttributeNames([
    'username' => 'Username',
    'email' => 'Email address',
    'password' => 'Password',
])->setCustomMessages([
    'required' => 'The :attribute field is required.',
    'email' => 'The :attribute must be a valid email address.',
    'unique' => 'The :attribute is already in use.',
    'min' => 'The :attribute must be at least :min characters long.',
    'max' => 'The :attribute may not be greater than :max characters.',
]);

if ($validator->fails()) {
    // Handle validation errors
}