Validation Flashcards
(118 cards)
What is a form request and how can you create one?
Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request Artisan CLI command:
php artisan make:request StorePostRequest
The generated form request class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Each form request generated by Laravel has two methods: authorize and rules.
As you might have guessed, the authorize method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules method returns the validation rules that should apply to the request’s data:
public function rules(): array { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; }
How are validation rules evaluated?
All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
public function store(StorePostRequest $request): RedirectResponse { // The incoming request is valid... // Retrieve the validated input data... $validated = $request->validated(); // Retrieve a portion of the validated input data... $validated = $request->safe()->only(['name'; 'email']); $validated = $request->safe()->except(['name', 'email']); // Store the blog post... return redirect('/posts'); }
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
How can you perform additional validation after your initial validation is complete?
You can accomplish this using the form request’s after method.
The after method should return an array of callables or closures which will be invoked after validation is complete. The given callables will receive an Illuminate\Validation\Validator instance, allowing you to raise additional error messages if necessary.
How can you inform the validator that it should stop validating all attributes once a single validation failure has occured?
By adding a stopOnFirstFailure property to your request class:protected $stopOnFirstFailure = true;
By default, a redirect response will be generated to send the user back to their previous location when form request validation fails. How can you change that?
You are free to customize this behavior. To do so, define a $redirect property on your form request.protected $redirect = '/dashboard';
Or, if you would like to redirect users to a named route, you may define a $redirectRoute property instead:protected $redirectRoute = 'dashboard';
The form request class also contains an authorize method, what does it do?
Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your authorization gates and policies within this method:
public function authorize(): bool { $comment = Comment::find($this->route('comment')); return $comment && $this->user()->can('update', $comment); }
How can you customize the error messages used by the form request?
You may customize them by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:
public function messages(): array { return [ 'title.required' => 'A title is required', 'body.required' => 'A message is required', ]; }
Many of Laravel’s build-in validation rule error messages contain an :attribute placeholder. How can you replace the :attribute placeholder of your validation message with a custom attribute name?
If you would like the :attribute placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:
public function attributes(): array { return [ 'email' => 'email address', ]; }
How can you prepare or sanitize any data from the request before you apply your validation rules?
If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:
protected function prepareForValidation(): void { $this->merge([ 'slug' => Str::slug($this->slug), ]); }
Likewise, if you need to normalize any request data after validation is complete, you may use the passedValidation method:
protected function passedValidation(): void { $this->replace(['name' => 'Taylor']); }
How can you manually create validators instead of using the validate method?
If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance. The first argument passed to make method is the data under validation. The second argument is an array of the validation rules that should be applied to the data. After determining whether the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.
How can you create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request’s validate method?
You may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a JSON response will be returned:
Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ])->validate();
You may use the validateWithBag method to store the error messages in a named error bag if validation fails:
Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ])->validateWithBag('post');
If you have multiple forms on a single page, you may wish to name the MessageBag containing the validation errors, allowing you to retrieve the error messages for a specific form. How can you achieve this?
To achieve this, pass a name as the second argument to withErrors:return redirect('/register')->withErrors($validator, 'login');
You may then access the named MessageBag instance from the $errors variable:{{ $errors->login->first('email') }}
Sometimes you may wish to specify a custom error message only for a specific attribute. How can you do that?
You may do so using dot notation. Specify the attribute’s name first, followed by the rule:
$messages = [ 'email.required' => 'We need to know your email address!', ];
Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. Which command lets you generate a new rule object?
To generate a new rule object, you may use the make:rule Artisan command. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:php artisan make:rule Uppercase
Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: validate. This method receives the attribute name, its value, and a call back that should be invoked on failure with the validation error message:
public function validate(string $attribute, mixed $value, Closure $fail): void { if (strtoupper($value) !== $value) { $fail('The :attribute must be uppercase.'); } }
If you only need toe functionality of a custom rule once throughout your application, how can you achieve that without making a rule object?
You may use a closure. The closure receives the attribute’s name, the attribute’s value, and a $fail callback that should be called if validation fails:
$validator = Validator::make($request->all(), [ 'title' => [ 'required', 'max:255', function (string $attribute, mixed $value, Closure $fail) { if ($value === 'foo') { $fail("The {$attribute} is invalid."); } }, ], ]);
What does the accepted rule do?
The field under validation must be “yes”, “on”, 1, “1”, true, or “true”. This is useful for validating “Terms of Service” acceptance or similar fields.
What does the active_url rule do?
The field under validation must have a valid A or AAAA record according to the dns_get_record
PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record
What does the after:date rule do?
The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function in order to be converted to a valid DateTime instance:'start_date' => 'required|date|after:tomorrow'
Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:'finish_date' => 'required|date|after:start_date'
What does the after_or_equal:date rule do?
The field under validation must be a value after or equal to the given date.
What does the alpha rule do?
The field under validation must be entirely Unicode alphabetic characters contained in \p{L} and \p{M}.
To restrict this validation rule to characters in the ASCII range (a-z and A-Z), you may provide the ascii option to the validation rule:'username' => 'alpha:ascii',
What does the alpha_dash rule do?
Same as alpha_num, but also allows - and _
What does the alpha_num rule do?
The field under validation must be entirely Unicode alpha-numeric characters contained in \p{L}, \p{M}, and \p{N}.
To restrict this validation rule to characters in the ASCII range (a-z and A-Z), you may provide the ascii option to the validation rule:
‘username’ => ‘alpha_num:ascii’,
What does the array rule do?
The field under validation must be a PHP array.
When additional values are provided to the array rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the admin key in the input array is invalid since it is not contained in the list of values provided to the array rule. In general, you should always specify the array keys that are allowed to be present within your array.
What does the ascii rule do?
The field under validation must be entirely 7-bit ASCII characters.