Unit 5 subjective questions Laravel Form validation
INT221 — Mvc Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Explain the concept of CSRF protection in Laravel and how to implement it in a form.
Model answer
Cross-Site Request Forgery (CSRF) is a malicious exploit where unauthorized commands are transmitted from a user that the web application trusts. Laravel automatically protects against this using a CSRF token.\n\nHow it works:\n1. Laravel generates a
csrf_tokenfor each active user session.\n2. This token is verified by theVerifyCsrfTokenmiddleware.\n3. If the token in the request does not match the session token, a HTTP 419 error is generated.\n\nImplementation:\nInside an HTML form defined in a Blade template, you must include the CSRF token field. This can be done using the@csrfBlade directive:\n\nhtml
<form method="POST" action="/profile">
@csrf
...
</form>
\n\nAlternatively, you can use{{ csrf_field() }}which generates the following HTML:\nhtml
<input type="hidden" name="_token" value="GeneratedTokenHere"> -
Question 2 of 20
What is Method Spoofing in Laravel forms, and why is it necessary for RESTful resource controllers?
Model answer
HTML forms primarily support
GETandPOSTHTTP verbs. However, RESTful routing often requiresPUT,PATCH, orDELETEmethods to update or destroy resources.\n\nMethod Spoofing is a technique used to trick the application into treating a form submission as a different HTTP verb than what is natively supported by the browser.\n\nImplementation:\nTo spoil the method, you add a hidden input field named_methodcontaining the desired HTTP verb. Laravel provides the@methodBlade directive for this:\n\nhtml
<form action="/post/1" method="POST">
@csrf
@method('PUT')<input type="text" name="title"> <button type="submit">Update</button></form>
\n\nWhen processed, Laravel sees the_methodfield and routes the request as aPUTrequest. -
Question 3 of 20
Describe the standard process of validating form data in a Laravel Controller using the
validatemethod.Model answer
The
validatemethod provided by theIlluminate\Http\Requestobject is the most common way to validate incoming data.\n\nProcess Flow:\n1. Define Rules: Pass an array of validation rules to thevalidatemethod.\n2. Execution: Laravel checks the incoming HTTP request parameters against these rules.\n3. Success: If validation passes, the code execution continues normally.\n4. Failure: If validation fails, Laravel throws aValidationException.\n If it is a standard HTTP request, a redirect response is generated back to the previous URL with error messages flashed to the session.\n If it is an XHR (AJAX) request, a JSON response with the validation errors is returned.\n\nExample:\nphp
public function store(Request $request) {
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);// Proceed to save data...}
-
Question 4 of 20
List and explain five common Validation Rules available in Laravel.
Model answer
Laravel provides a wide variety of validation rules. Here are five common ones:\n\n1.
required: The field must be present in the input data and not be empty. A field is considered "empty" if it is null or an empty string.\n2.email: The field must be formatted as a valid email address (e.g.,user@example.com).\n3.numeric: The field under validation must be numeric (can be an integer or a string representing a number).\n4.min:value/max:value: Used to specify size constraints.\n For strings, it corresponds to the number of characters.\n For numbers, it corresponds to the integer value.\n * For files, it corresponds to the file size in kilobytes.\n5.unique:table,column: The field must not exist within the given database table. For example,unique:users,emailensures no other user has registered with that email address. -
Question 5 of 20
How can you display validation error messages in a Blade view file?
Model answer
When validation fails, Laravel shares an
$errorsvariable (an instance ofIlluminate\Support\MessageBag) with all views. There are two primary ways to display these errors:\n\n1. Checking for specific field errors:\nUse the@errordirective to check if a specific attribute has an error message.\nhtml
<label for="title">Post Title</label>
<input id="title" type="text" name="title" class="@error('title') is-invalid @enderror">@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
\n\n2. Displaying all errors:\nYou can iterate through all errors if you wish to show a summary list.\nhtml
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif -
-
Question 6 of 20
Explain the concept of Repopulating Forms using the
old()helper function.Model answer
When validation fails, Laravel redirects the user back to the form. To provide a good user experience, the form should retain the data the user previously typed so they don't have to re-enter everything.\n\nThe
old()Helper:\nLaravel flashes the input data to the session during the redirect. The globalold()helper retrieves this flashed data.\n\nSyntax:old('input_name', 'default_value')\n\nExample Usage in Blade:\nhtml
<label>Username</label>
<input type="text" name="username" value="{{ old('username') }}">
\n\nIf the form was submitted and failed validation, the input will contain the previous value. If the form is loaded for the first time, it will be empty (or the default value provided). -
Question 7 of 20
How do you create and use a Custom Validation Rule object in Laravel?
Model answer
For complex validation logic that isn't covered by built-in rules, you can create a custom Rule object.\n\n1. Generate the Rule:\nRun the Artisan command:\n
php artisan make:rule Uppercase\n\n2. Define Logic:\nEdit the generated class inapp/Rules/Uppercase.php. Implement thevalidatemethod (in newer Laravel versions) orpassesandmessagemethods.\n\nphp
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}public function message()
{
return 'The :attribute must be uppercase.';
}
\n\n3. Apply the Rule:\nPass a new instance of the rule object in your controller's validation array.\n\nphp
use App\Rules\Uppercase;$request->validate([
'name' => ['required', 'string', new Uppercase],
]); -
Question 8 of 20
Differentiate between using Form Request Validation and Controller Validation.
Model answer
Controller Validation:\n Definition: Validation logic is written directly inside the controller method using
$request->validate().\n Pros: Quick to implement for simple forms.\n Cons: Can clutter the controller if rules are complex; violates 'Thin Controller' philosophy if overused.\n\nForm Request Validation:\n Definition: Validation logic is moved to a dedicated class (Request class) usually stored inapp/Http/Requests. Created viaphp artisan make:request.\n Structure: The class contains arules()method for validation rules and anauthorize()method for user permissions.\n Pros: Separation of concerns (cleaner controllers), reusable validation logic, automatic validation before the controller method is even called.\n\nExample Usage:\nInstead ofpublic function store(Request $request), you usepublic function store(StorePostRequest $request), and Laravel validates automatically. -
Question 9 of 20
What is the
confirmedvalidation rule, and how does it relate to form field naming conventions?Model answer
The
confirmedrule is typically used for password confirmation to ensure a user didn't make a typo when creating a password.\n\nFunctionality:\nWhen you apply the rule'password' => 'confirmed', Laravel looks for a matching input field named exactly like the original field with_confirmationappended to it.\n\nHTML Requirement:\nIf the validation rule is applied to a field namedpassword, the HTML form must have two fields:\n1.name="password"\n2.name="password_confirmation"\n\nLogic:\nIf the values ofpasswordandpassword_confirmationdo not match, the validation fails. -
Question 10 of 20
How can you customize Validation Error Messages for specific fields?
Model answer
There are two main ways to customize error messages:\n\n1. Passing an array to the
validatemethod:\nThevalidatemethod accepts a second argument (and optionally a third for custom attribute names) where you define messages.\n\nphp
$request->validate(
['title' => 'required'],
['title.required' => 'We need a title to proceed!'] // Custom message
);
\n\n2. Using Form Request Classes:\nIf using a Form Request class, override themessages()method.\n\nphp
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
\n\nMessages generally follow the format'field.rule' => 'Message'. -
Question 11 of 20
Explain the concept of Stopping on First Failure using the
bailrule.Model answer
By default, Laravel validates all rules assigned to an attribute and collects all errors. If an attribute fails the first rule, Laravel continues checking the subsequent rules for that same attribute.\n\nThe
bailRule:\nIf you want validation on an attribute to stop immediately after the first validation failure, prepend thebailrule to the list.\n\nWhy use it?\nIt saves resources. For example, if a field isunique(which requires a database query) andinteger, checking foruniqueis wasteful if the input isn't even aninteger.\n\nExample:\nphp
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
]);
\nIftitleis missing (requiredfails), theuniquecheck (database query) is never executed. -
Question 12 of 20
How do you handle validation for Nested Attributes (arrays) in Laravel?
Model answer
When a form contains array inputs (e.g.,
<input name="items[][name]">), Laravel uses "dot notation" to validate these nested attributes.\n\nScenario:\nYou are submitting a list of products, where each product has a name and a quantity.\n\nValidation Rules:\n1. Validate the array itself: Ensureproductsis present and is an array.\n2. Validate items inside: Use the asterisk*wildcard.\n\nExample:\nphp
$request->validate([
'products' => 'required|array',
'products..name' => 'required|string',
'products..quantity' => 'required|integer|min:1',
]);
\n\nThe rule'products.*.name'validates thenameproperty of every item in theproductsarray. -
Question 13 of 20
Describe how to perform validation using Closures instead of creating a Rule object.
Model answer
For one-off custom validation logic that doesn't warrant creating a dedicated class file, you can use a Closure (anonymous function) directly in the validation rules array.\n\nSyntax:\nThe closure receives three arguments:
$attribute(field name),$value(input value), and$fail(callback to trigger failure).\n\nExample:\nValidating that a specific field usually equals "admin":\n\nphp
use Illuminate\Support\Facades\Validator;$request->validate([
'role' => [
'required',
function ($attribute, $value, $fail) {
if ($value !== 'admin') {
attribute.' is invalid.');
}
},
],
]);
\n\nThis method allows you to inject inline custom logic quickly within the controller. -
Question 14 of 20
Explain the
uniquevalidation rule with respect to ignoring a specific ID during updates.Model answer
The
uniquerule checks if a value exists in the database. A common issue arises during update operations: if a user updates their profile but keeps their current email address, the standarduniquerule will fail because the email already exists in the database (associated with the user themselves).\n\nSolution:\nYou must instruct the validator to ignore the specific user ID that is currently being updated.\n\nSyntax:\nunique:table,column,except,idColumn\n\nExample (Raw String):\nphp
// Assuming updating a user with ID 5
'email' => 'required|email|unique:users,email,5'
\n\nExample (Fluent / Rule Class):\nThis is cleaner and preferred in modern Laravel:\nphp
use Illuminate\Validation\Rule;'email' => [
'required',
Rule::unique('users')->ignore($user->id),
], -
Question 15 of 20
How does Laravel handle Optional Fields that must be validated only if present?
Model answer
Laravel provides two primary mechanisms for optional fields:\n\n1. The
nullablerule:\n This implies that the field can benull. If the field isnull, subsequent validation rules are skipped. If it contains data, it must pass the other rules.\n Example:'bio' => 'nullable|string|max:1000'(Bio can be empty, but if provided, must be a string under 1000 chars).\n\n2. Thesometimesrule:\n This runs validation checks only if that field is present in the$requestdata array.\n Example: You have a single update endpoint for email and password, but sometimes you only send email. \n'password' => 'sometimes|required|min:8'\n If thepasswordfield is not in the form submission (not in the DOM), the validation is skipped completely. -
Question 16 of 20
Discuss how to repopulate checkboxes and select menus using the
old()helper.Model answer
Repopulating standard text inputs is straightforward (
value="{{ old('name') }}"), but checkboxes and select menus require conditional logic to set thecheckedorselectedattributes.\n\n1. Select Menus:\nYou verify if theoldvalue matches the option value.\nhtml
<select name="role">
<option value="admin" {{ old('role') == 'admin' ? 'selected' : '' }}>Admin</option>
<option value="user" {{ old('role') == 'user' ? 'selected' : '' }}>User</option>
</select>
\n\n2. Checkboxes:\nSimilar logic is used to output thecheckedattribute.\nhtml
<input type="checkbox" name="terms" value="1" {{ old('terms') ? 'checked' : '' }}>
\n\nHandling Edit Forms:\nOften, you need to check against theoldinput first (in case of validation error), and fallback to the database value (model value). \nExample:old('role', $user->role) == 'admin' ? 'selected' : ''. -
Question 17 of 20
What are the requirements for validating a file upload (e.g., an image) in Laravel?
Model answer
Validating file uploads involves checking the file type (MIME type), file extension, and file size.\n\nKey Rules:\n1.
file: Validates that the input is a successfully uploaded file.\n2.mimes:foo,bar: Validates the MIME type/extension (e.g.,jpeg,png,bmp).\n3.max:value: Validates the file size in Kilobytes (KB).\n4.image: A shortcut rule that ensures the file is a jpeg, png, bmp, gif, svg, or webp.\n\nExample:\nphp
$request->validate([
'avatar' => 'required|file|image|mimes:jpeg,png|max:2048',
]);
\nThis ensures an avatar is uploaded, is an image, is specifically a jpeg or png, and is no larger than 2MB. -
Question 18 of 20
Explain the role of the
$errorsvariable and theIlluminate\Support\MessageBaginstance in Laravel views.Model answer
The
$errorsVariable:\nIn Laravel, theShareErrorsFromSessionmiddleware ensures that an$errorsvariable is always available in all views. This variable is an instance ofIlluminate\Support\MessageBag.\n\nIf no errors exist:\nThe variable is still present but empty, allowing developers to use it without checkingisset().\n\nFeatures of MessageBag:\nIt provides convenient methods to retrieve error messages:\n1.any(): Returns booleantrueif there are any errors.\n2.all(): Returns an array of all error messages.\n3.has('field'): Checks if a specific field has an error.\n4.first('field'): Returns the first error message for a given field (useful since a field can have multiple errors).\n\nExample:\n{{ $errors->first('email') }}outputs just the first error message for the email field. -
Question 19 of 20
How does Laravel localize validation error messages?
Model answer
Laravel supports multi-language applications by storing validation messages in language files.\n\nLocation:\nDefault messages are stored in
lang/en/validation.php(orresources/lang/en/validation.phpin older versions).\n\nStructure:\nThis file returns an array where keys are the validation rules and values are the messages.\nphp
return [
'required' => 'The :attribute field is required.',
'email' => 'The :attribute must be a valid email address.',
];
\n\nCustomizing Attributes:\nTo replace:attributewith a user-friendly name (e.g., "Email Address" instead of "email"), thevalidation.phpfile contains anattributesarray at the bottom:\nphp
'attributes' => [
'email' => 'email address',
],
\nTo support a new language (e.g., Spanish), you would createlang/es/validation.phpand translate the messages. -
Question 20 of 20
Write a short note on the
dateanddate_formatvalidation rules.Model answer
These rules ensure that input data represents valid dates.\n\n1.
daterule:\nThis rule validates that the input is a valid, non-relative date according to the PHPstrtotimefunction.\n Example:'start_date' => 'required|date'\n\n2.date_formatrule:\nThis rule is stricter and ensures the input matches a specific format defined by PHP'sdate_create_from_formatfunction.\n Example:'dob' => 'required|date_format:Y-m-d'\n This ensures the user enters the date exactly as2023-10-25.\n\nComparisons:\nYou can also compare dates using rules likeafter:date,after_or_equal:date,before:date.\n Example:'end_date' => 'required|date|after:start_date'.
That's unit 5
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 5 of INT221 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 5 of INT221 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.