Unit 4 subjective questions URL Generation, Request Data and Emails
INT221 — Mvc Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Explain how to retrieve all input data from an incoming HTTP request in Laravel. How does it differ from retrieving a specific input value?
Model answer
In Laravel, the
Illuminate\Http\Requestinstance provides several methods to retrieve user input.Retrieving All Input
To retrieve all incoming request input data as an array, you can use the
allmethod. This returns an array containing all input values, regardless of whether they came from the query string or the POST body.PHP$input = $request->all();Retrieving Specific Input
To retrieve a single input value, use the
inputmethod. This method accepts the name of the input field as the first argument and an optional default value as the second argument.PHP$name = $request->input('name'); $name = $request->input('name', 'Sally'); // With default valueDifference:
all()returns an associative array of all input keys and values.input()returns a specific scalar value (string, integer, etc.) ornull/default if the key does not exist.
-
Question 2 of 20
Discuss the methods available in Laravel to determine if an input value is present in the request.
Model answer
Laravel provides specific methods on the Request instance to check for the presence of input data:
-
has() Method:
Thehasmethod returnstrueif the value is present on the request. It can check for a single value or an array of values.
php
if ($request->has('email')) {
// ...
} -
whenHas() Method:
This method executes a closure if a value is present.
php
input) {
// ...
}); -
filled() Method:
Thefilledmethod returnstrueif a value is present on the request and is not empty.
php
if ($request->filled('email')) {
// ...
} -
missing() Method:
Themissingmethod returnstrueif the value is not present on the request.
php
if ($request->missing('name')) {
// ...
}
-
-
Question 3 of 20
What is the concept of "Old Input" in Laravel? Describe how to flash input to the session and retrieve it subsequently.
Model answer
Concept of Old Input
Laravel allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. This data is stored in a temporary session (flash data).
Flashing Input
The
flashmethod on theRequestinstance will flash the current input to the session so that it is available during the user's next request to the application.PHP$request->flash();You can also flash only specific input using
flashOnlyorflashExcept:PHP$request->flashOnly(['username', 'email']); $request->flashExcept('password');Retrieving Old Input
To retrieve flashed input from the previous request, use the
oldmethod on theRequestinstance.PHP$username = $request->old('username');In Blade templates, the global helper
old()is commonly used to repopulate form values:HTML<input type="text" name="username" value="{{ old('username') }}"> -
Question 4 of 20
How does Laravel handle uploaded files? Explain how to access an uploaded file and verify its validity.
Model answer
In Laravel, uploaded files are handled via the
Illuminate\Http\Requestinstance.Accessing Uploaded Files
You can access uploaded files using the
filemethod or using dynamic properties. The method returns an instance ofIlluminate\Http\UploadedFile, which extends the PHPSplFileInfoclass.PHP// Using method $file = $request->file('photo'); // Using dynamic property $file = $request->photo;Verifying Validity
Before processing a file (e.g., moving or storing it), it is crucial to verify that the file was uploaded successfully without errors. This is done using the
isValidmethod:PHPif ($request->file('photo')->isValid()) { // The file was uploaded successfully... }This checks if there were any upload errors (like exceeding
upload_max_filesizein php.ini) during the HTTP transfer. -
Question 5 of 20
Describe the process of storing uploaded files in Laravel using the
storemethod. Provide a syntax example.Model answer
Laravel's
UploadedFileclass provides astoremethod to save an uploaded file to one of the configured filesystems (local, S3, etc.).The
storeMethodThe
storemethod accepts the path where the file should be stored relative to the filesystem's root configured directory. It generates a unique ID to serve as the filename.Syntax:
php
$path = $request->file('avatar')->store('path/to/directory');Specifying Disk
You can specify a storage disk (defined in
config/filesystems.php) as the second argument:PHP$path = $request->file('avatar')->store('avatars', 's3');Storing with Original Name
If you do not want a randomly generated filename, you can use
storeAs:PHP$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id . '_avatar.jpg' );The method returns the path to the file relative to the disk's root.
-
-
Question 6 of 20
Explain how to retrieve Cookies in Laravel. How does the Laravel framework ensure the security of cookies?
Model answer
Retrieving Cookies
Cookies in Laravel can be retrieved from the
Illuminate\Http\Requestinstance using thecookiemethod.PHP$value = $request->cookie('name');Alternatively, you can use the
Cookiefacade:
php
use Illuminate\Support\Facades\Cookie;
$value = Cookie::get('name');Security (Encryption)
By default, all cookies created by Laravel are encrypted and signed.
- Encryption: Ensures the contents of the cookie cannot be viewed by the client.
- Signing: Ensures the cookie is not modified by the client.
When a cookie is retrieved, Laravel automatically decrypts it. If the cookie has been tampered with, the value will be invalid and discarded. This relies on the
APP_KEYdefined in the.envfile. -
Question 7 of 20
How can you attach a Cookie to an outgoing Response in Laravel? Explain the usage of
Cookie::queue.Model answer
Attaching to Response
In Laravel, cookies are typically attached to the outgoing
Illuminate\Http\Responseinstance using thewithCookiemethod or thecookiehelper.PHPreturn response('Hello World')->cookie( 'name', 'value', $minutes );Using Cookie::queue
Often, you might want to set a cookie before the response instance has been created (e.g., inside a controller action or middleware). The
Cookie::queuemethod allows you to queue a cookie to be attached to the response automatically when it is eventually sent by the framework.PHPuse Illuminate\Support\Facades\Cookie; // Queue the cookie for the next response Cookie::queue('name', 'value', 60);This places the cookie in a temporary storage, and the
AddQueuedCookiesToResponsemiddleware attaches it to the HTTP response headers. -
Question 8 of 20
What are 'Mailables' in Laravel? Describe the structure of a Mailable class and its
buildmethod.Model answer
Mailables
In Laravel, each type of email sent by the application is represented as a "Mailable" class. These classes are stored in the
app/Maildirectory. They encapsulate the logic for building the email, including the subject, view, and attachments.Structure of a Mailable Class
A Mailable class typically extends
Illuminate\Mail\Mailableand uses theQueueableandSerializesModelstraits.The
buildMethodAll logic for configuring the email is done inside the
buildmethod. Within this method, you call various methods likefrom,subject,view, andattachto configure the email's presentation and delivery.Example:
php
public function build()
{
return $this->from('example@example.com')
->subject('Order Shipped')
->view('emails.orders.shipped');
}Data required by the view is usually passed via the class constructor and assigned to public properties, which are automatically available in the view.
-
Question 9 of 20
Write the code snippet to send an email using the
Mailfacade in Laravel.Model answer
To send a message, use the
tomethod on theMailfacade. Thetomethod accepts an email address, a user instance, or a collection of users. Once the recipient is specified, pass an instance of the Mailable class to thesendmethod.Code Snippet:
PHPnamespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\OrderShipped; use App\Models\Order; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class OrderController extends Controller { public function store(Request $request) { $order = Order::findOrFail($request->order_id); // Send the email Mail::to($request->user())->send(new OrderShipped($order)); } } -
Question 10 of 20
Explain the concept of Laravel Localization. How are translation strings stored and retrieved?
Model answer
Laravel Localization
Laravel's localization features allow applications to support multiple languages by retrieving strings in various languages easily. It provides a convenient way to retrieve strings from language files based on the current locale of the application.
Storing Translation Strings
Translations are stored in the
lang(orresources/lang) directory. There are two supported methods:-
Short Keys (PHP files):
Used for structured data. Files are stored in directories named after the locale (e.g.,lang/en/messages.php).
php
// lang/en/messages.php
return [
'welcome' => 'Welcome to our application',
]; -
JSON Strings:
Used for applications with many translation strings. Files are stored as JSON files in the root of the lang directory (e.g.,lang/es.json).{
"I love programming.": "Me encanta programar."
}
Retrieval
Strings are retrieved using the
__helper function or the@langBlade directive.PHPecho __('messages.welcome'); echo __('I love programming.'); -
-
Question 11 of 20
How do you handle parameters/placeholders in Laravel Localization strings? Provide an example.
Model answer
Laravel allows you to define placeholders in translation strings. These placeholders usually start with a colon
:. When retrieving the string, you pass an array of replacements as the second argument to the translation function.Defining the String (e.g., in
lang/en/messages.php):
php
'welcome' => 'Welcome, :name',Retrieving with Replacement:
To replace:namewith a dynamic value:PHPecho __('messages.welcome', ['name' => 'John']);Output:
Welcome, JohnCapitalization:
If the placeholder is capitalized (:Name), the replacement value will be capitalized automatically (e.g.,johnbecomesJohn). If it is all caps (:NAME), the value becomes all caps. -
Question 12 of 20
What are Laravel Sessions? List and briefly describe three available session drivers.
Model answer
Laravel Sessions
Since HTTP is stateless, sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends that are accessed through a unified API.
Available Session Drivers
Configuration is found in
config/session.php. Common drivers include:- file: Sessions are stored in
storage/framework/sessions. This is the default driver. - cookie: Sessions are stored securely in encrypted cookies on the user's browser.
- database: Sessions are stored in a relational database. This requires a table (typically named
sessions) to store the session ID and payload. - redis / memcached: Sessions are stored in these fast, cache-based stores, ideal for high-performance applications.
- file: Sessions are stored in
-
Question 13 of 20
Explain how to access session data in Laravel using both the
Requestinstance and the globalsessionhelper.Model answer
There are two primary ways to access session data in Laravel:
1. Using the Request Instance
The
Illuminate\Http\Requestinstance allows access via thesession()method.PHPpublic function show(Request $request, $id) { $value = $request->session()->get('key'); // With a default value if 'key' is missing $value = $request->session()->get('key', 'default'); }2. Using the Global Session Helper
The global
session()helper allows access anywhere in the application (controllers, views, etc.).-
Retrieving: Pass the key name.
php
$value = session('key');
$value = session('key', 'default'); -
Storing: Pass an array of key/value pairs.
php
session(['key' => 'value']);
-
-
Question 14 of 20
Describe the methods used to store data in the Laravel Session. Distinguish between
putandpush.Model answer
To store data in the session, you generally use the session instance retrieved via the request or the helper.
1. The
putMethodThe
putmethod is used to store a specific key-value pair in the session.PHP// Via Request $request->session()->put('key', 'value'); // Via Helper session(['key' => 'value']);2. The
pushMethodThe
pushmethod is used when the session value is an array. It allows you to push a new value onto an array that is already stored in the session.PHP$request->session()->push('user.teams', 'developers');Distinction:
put: Sets or overwrites a value for a specific key.push: Appends a value to an array associated with the key.
-
Question 15 of 20
How can you retrieve and delete an item from the session in a single statement? Also, explain how to delete specific items versus all items.
Model answer
Retrieve and Delete (
pull)The
pullmethod retrieves an item from the session and immediately removes it from the storage.PHP$value = $request->session()->pull('key', 'default');Deleting Specific Items (
forget)The
forgetmethod removes a specific piece of data (or multiple pieces) from the session.PHP// Forget a single key $request->session()->forget('key'); // Forget multiple keys $request->session()->forget(['key1', 'key2']);Deleting All Items (
flush)The
flushmethod removes all data from the session.PHP$request->session()->flush(); -
Question 16 of 20
Explain the concept of "Flash Data" in Laravel sessions. Why is it useful and how is it implemented?
Model answer
Concept
Flash data refers to session data that is stored only for the immediate next request, after which it is automatically deleted.
Use Case
This is primarily used for short-lived status messages, such as displaying a "Task created successfully!" banner after a form submission redirects the user to a list page.
Implementation
Use the
flashmethod on the session instance.PHP$request->session()->flash('status', 'Task was successful!');In the subsequent request (e.g., in a Blade view), you check for it like normal session data:
HTML@if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endifIf you need to keep flash data for one more request (e.g., across multiple redirects), you can use the
reflashorkeepmethods. -
Question 17 of 20
What is the importance of Regenerating the Session ID? How is it done in Laravel?
Model answer
Importance
Regenerating the session ID is a critical security practice to prevent Session Fixation attacks. In such attacks, a malicious user fixes another user's session ID effectively hijacking the session.
By regenerating the ID (changing the underlying unique identifier string while keeping the session data) immediately after sensitive actions—like logging in—you ensure that any ID an attacker might possess becomes invalid.
Implementation in Laravel
Laravel automatically regenerates the session ID during authentication via its built-in auth controllers. However, if you are manually handling session logic, you can use the
regeneratemethod.PHP$request->session()->regenerate();This method generates a new session ID and invalidates the old one.
-
Question 18 of 20
Explain the
urlandroutehelpers for URL Generation in Laravel.Model answer
Laravel provides helpers to generate URLs for your application.
The
urlHelperThe
urlhelper is used to generate arbitrary URLs for the application. It will automatically handle the HTTP/HTTPS protocol and the host definition.PHP$url = url('/posts'); // With current query parameters $current = url()->current();The
routeHelperThe
routehelper generates URLs for named routes. This is preferred because if the URL path changes in the definition (routes/web.php), you do not need to update your views or controllers, as long as the route name remains the same.Route Definition:
php
Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile');Generating URL:
php
$url = route('profile');If the route accepts parameters:
php
$url = route('profile', ['id' => 1]);
// Result: http://your-app.com/user/profile?id=1 (or path param if defined) -
Question 19 of 20
How do you check for input data in an array format using dot notation in Laravel?
Model answer
When working with forms that contain arrays of inputs (e.g.,
<input name="products[0][name]">), Laravel allows you to access these values and check for their existence using "dot" notation.Checking Existence
You can pass a string containing dots to the
hasmethod:PHPif ($request->has('products.0.name')) { // The name of the first product exists } if ($request->has(['products.0.name', 'products.0.price'])) { // Both exist }Retrieving Data
Similarly, you can retrieve the data using dot notation:
PHP$productName = $request->input('products.0.name');You can also use the wildcard character
*to retrieve data for all elements in the array:PHP$names = $request->input('products.*.name'); // Returns an array of names for all products -
Question 20 of 20
Compare the usage of
CookieandSessionin Laravel with regards to data persistence and storage location.Model answer
While both Cookies and Sessions are used to store data across requests, they differ significantly in implementation and use cases.
Feature Cookie Session Storage Location Stored on the Client-side (User's browser). Stored on the Server-side (File, DB, Redis) (The ID is stored in a cookie). Capacity Limited (usually around 4KB). Limited only by server resources. Security Susceptible to theft if not secure/HttpOnly. Laravel encrypts them, but they still physically exist on the client. More secure. The client only holds the Session ID reference; actual data is never exposed to the browser. Persistence Can be set to expire after a long time (even after browser close). Usually expires when the browser is closed or after a specific timeout defined in config. Laravel Access Cookie::get('key')or$request->cookie().session('key')or$request->session()->get().Typical Use "Remember Me" tokens, tracking IDs, user preferences (theme). User Authentication state, Shopping cart, Flash messages.
That's unit 4
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 4 of INT221 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 4 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.