Unit 3 subjective questions Controllers, Blade and Advanced Routing
INT221 — Mvc Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define a Controller in MVC programming and explain how to create a basic controller using Artisan commands.
Model answer
Definition:
In MVC (Model-View-Controller) architecture, a Controller acts as an intermediary between the Model and the View. It handles the user's request, retrieves necessary data from the Model, processes it, and returns the appropriate View to the user. Controllers group related request handling logic into a single class.Creating a Controller:
Laravel (and similar MVC frameworks) allows developers to create controllers via the command line interface (Artisan).-
Command: To create a basic controller, use the following command in the terminal:
bash
php artisan make:controller NameOfController -
Location: The file is created in the
app/Http/Controllersdirectory. -
Structure: A basic controller class extends the base Controller class.
php
namespace App\Http\Controllers;
use Illuminate\Http\Request;class UserController extends Controller
{
public function show($id)
{
return view('user.profile', ['id' => $id]);
}
}
-
-
Question 2 of 20
Explain the concept of Controller Routing with a syntax example. How does it differ from closure-based routing?
Model answer
Controller Routing:
Instead of defining all request handling logic inside the route file (closure-based routing), Controller Routing allows you to point a route to a specific action (method) within a Controller class. This promotes cleaner code and better organization.Syntax:
To define a route that points to a controller action, you use the following syntax in theroutes/web.phpfile:PHPuse App\Http\Controllers\UserController; // Route::verb('uri', [ControllerClass::class, 'methodName']); Route::get('/user/{id}', [UserController::class, 'show']);Difference from Closure Routing:
- Closure Routing: The logic is written directly in the route definition using an anonymous function. Good for small, simple routes.
- Controller Routing: The logic is encapsulated in a class. This is preferred for larger applications as it supports dependency injection, route caching, and better separation of concerns.
-
Question 3 of 20
What are Restful Resource Controllers? List the default actions generated by a resource controller.
Model answer
Restful Resource Controllers:
Resource routing assigns the typical "CRUD" (Create, Read, Update, Delete) routes to a controller with a single line of code. A Resource Controller contains methods for each of these operations corresponding to HTTP verbs (GET, POST, PUT/PATCH, DELETE).Creating a Resource Controller:
bash
php artisan make:controller PhotoController --resourceDefault Actions:
A standard resource controller includes the following methods:- index: Display a listing of the resource. (GET)
- create: Show the form for creating a new resource. (GET)
- store: Store a newly created resource in storage. (POST)
- show: Display the specified resource. (GET)
- edit: Show the form for editing the specified resource. (GET)
- update: Update the specified resource in storage. (PUT/PATCH)
- destroy: Remove the specified resource from storage. (DELETE)
-
Question 4 of 20
Discuss how Middleware can be assigned within a Controller. Provide an example.
Model answer
Controller Middleware:
While middleware is often assigned in the route files, it is also possible to specify middleware directly within the Controller's constructor. This allows for more granular control over which methods require specific middleware (e.g., authentication).Usage:
You use themiddlewaremethod within the__constructmethod of the controller.Example:
php
class UserController extends Controller
{
public function __construct()
{
// Apply 'auth' middleware to all methods
$this->middleware('auth');// Apply 'log' middleware only to 'index' and 'show' methods $this->middleware('log')->only(['index', 'show']); // Apply 'subscribed' middleware to everything except 'store' $this->middleware('subscribed')->except('store'); }}
This approach ensures that the access control logic is kept close to the controller logic itself.
-
Question 5 of 20
What is Blade in the context of PHP MVC frameworks? Explain how to display PHP Output using Blade syntax.
Model answer
Blade:
Blade is the powerful, simple templating engine provided with Laravel. Unlike other PHP templating engines, Blade does not restrict you from using plain PHP code in your views. All Blade views are compiled into plain PHP code and cached until they are modified, adding essentially zero overhead to the application.PHP Output in Blade:
Blade uses specific syntax to echo data.-
Displaying Data (Escaped):
To display a variable, wrap it in double curly braces. This automatically runs the data through PHP'shtmlspecialcharsfunction to prevent XSS attacks.
blade
Hello, {{ $name }}. -
Displaying Unescaped Data:
If you need to display data that contains HTML (and you trust the source), use the following syntax:
blade
Hello, {!! $name !!}. -
Rendering JSON:
To render a variable as JSON (useful for JavaScript data), Blade provides the@jsondirective:
blade
var data = @json($array);
-
-
-
Question 6 of 20
Explain the usage of Control Structures in Blade templates with examples for Conditional Statements and Loops.
Model answer
Blade provides convenient shortcuts for common PHP control structures using directives starting with
@.1. Conditional Statements:
-
@if, @elseif, @else: used exactly like PHP.
blade
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif -
@unless: Equivalent to
if (! condition).
blade
@unless (Auth::check())
You are not signed in.
@endunless
2. Loops:
-
@foreach: Loops over an array or collection.
blade
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach -
@for: Standard for loop.
blade
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor -
@forelse: An explicit loop that handles the case where the array is empty.
blade
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users found</p>
@endforelse
-
-
Question 7 of 20
Describe Template Inheritance in Blade. How do
@extends,@section, and@yieldwork together?Model answer
Template Inheritance:
This is one of Blade's primary features, allowing developers to define a base "master" layout and have child views extend that layout. This eliminates code duplication (like headers, footers, and HTML structures).Key Directives:
-
@yield('name'):
Used in the Parent/Master layout. It defines a placeholder where content from a child view will be injected.
Example (layouts/app.blade.php):
blade
<html>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html> -
@extends('layout'):
Used in the Child view. It specifies which parent layout the view uses. -
@section('name') ... @endsection:
Used in the Child view. It defines the actual content that should be injected into the@yieldsection of the parent.
Example (child.blade.php):
blade
@extends('layouts.app')@section('content')
<p>This is the body content.</p>
@endsection
When
child.blade.phpis rendered, Blade combines the layout and the section content into a single HTML result. -
-
Question 8 of 20
What are Named Routes? Explain their benefits and provide a syntax example.
Model answer
Named Routes:
Named routes allow the convenient generation of URLs or redirects for specific routes. Instead of referring to a route by its hardcoded URI (e.g.,/user/profile), you refer to it by a unique name assigned during definition.Syntax:
You chain thenamemethod onto the route definition.
php
Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile');Benefits:
- Maintainability: If the route's URI changes (e.g., from
/user/profileto/u/profile), you do not need to change any code that generates links to that route, as the name remains'profile'. - Readability: Code like
route('profile')is often more semantic than hardcoded paths.
Usage:
- Generating URLs:
$url = route('profile'); - Redirecting:
return redirect()->route('profile');
- Maintainability: If the route's URI changes (e.g., from
-
Question 9 of 20
Explain Route Groups and how they help in organizing routes. Give examples of grouping by Middleware and Prefix.
Model answer
Route Groups:
Route groups allow you to share route attributes, such as middleware, namespaces, or prefixes, across a large number of routes without needing to define those attributes on each individual route. This keeps theroutes/web.phpfile clean and DRY (Don't Repeat Yourself).1. Middleware Grouping:
Useful for protecting a set of routes (e.g., requiring login).
php
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
// Uses Auth middleware
});
Route::get('/account', function () {
// Uses Auth middleware
});
});2. Route Prefixing:
Useful for grouping routes under a common URI segment (e.g., admin panels).
php
Route::prefix('admin')->group(function () {
// Matches URL "/admin/users"
Route::get('/users', function () {
// ...
});
}); -
Question 10 of 20
What are Parameter Constraints in routing? How can you enforce constraints using Regular Expressions?
Model answer
Parameter Constraints:
Sometimes you need to restrict the format of route parameters. For example, a user ID might strictly need to be numeric, or a username might need to be alphabetic. Parameter constraints validate these segments before the route is matched.Using Regular Expressions:
You can use thewheremethod on a route instance to constrain the format of parameters.Examples:
-
Numeric Constraint:
php
Route::get('/user/{id}', function ($id) {
// Only executed if {id} is numeric
})->where('id', '[0-9]+'); -
Alphabetic Constraint:
php
Route::get('/user/{name}', function ($name) {
// Only executed if {name} is letters
})->where('name', '[A-Za-z]+'); -
Multiple Constraints:
php
Route::get('/user/{id}/{name}', function ($id, $name) {
// ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
If the constraint fails, the router will treat the route as not matching and may return a 404 error.
-
-
Question 11 of 20
Explain Domain Routing. How can you route requests based on subdomains?
Model answer
Domain Routing:
Domain routing allows an application to handle routes differently based on the domain or subdomain of the incoming request. This is particularly useful for multi-tenant applications (e.g.,slack.comwhere every company hascompany.slack.com).Implementation:
You use thedomainmethod within a route group definition. You can also capture parts of the domain as parameters.Syntax Example:
php
Route::domain('{account}.myapp.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
// $account will be the subdomain (e.g., 'marketing')
// $id will be the user ID
return "Viewing user $id on the $account account.";
});
});In this example, if a user visits
marketing.myapp.com/user/1, the$accountvariable will contain "marketing". -
Question 12 of 20
How does the framework handle URL Generation? Explain the helpers for generating the Current URL.
Model answer
URL Generation:
The framework provides helpers to generate arbitrary URLs for the application. These serve to build links in templates, API responses, or redirection responses.Current URL Helpers:
There are several methods to retrieve information about the current request URL using theurl()helper or theRequestfacade:-
Get the Current URL (without query string):
php
// Returns: http://example.com/foo/bar
echo url()->current(); -
Get the Current URL (including query string):
php
// Returns: http://example.com/foo/bar?key=value
echo url()->full(); -
Get the Previous URL:
php
echo url()->previous();
These helpers ensure that the scheme (HTTP vs HTTPS) and host are correctly determined based on the incoming request.
-
-
Question 13 of 20
Differentiate between Generating Framework URLs and Asset URLs with examples.
Model answer
Generating Framework URLs:
These are URLs that point to application routes managed by the controller/routing logic. They are typically used for navigation within the app (e.g., clicking a link to view a post).- Helper:
url()orroute(). - Example:
url('/posts/1')generateshttp://yoursite.com/posts/1.
Asset URLs:
These URLs point to static files located in thepublicdirectory, such as CSS, JavaScript, or Images. They do not pass through the routing logic or controllers.- Helper:
asset(). - Example:
asset('css/style.css')generateshttp://yoursite.com/css/style.css.
Key Distinction:
Framework URLs process logic (PHP), while Asset URLs serve static content directly from the server's public folder. - Helper:
-
Question 14 of 20
What are Secure Routes? How can you generate URLs that force HTTPS?
Model answer
Secure Routes:
Secure routes refer to routes that are accessed over the HTTPS protocol using SSL/TLS encryption. Ensuring routes are secure is vital for protecting sensitive data like passwords and payment information.Generating Secure URLs:
The framework allows you to generate URLs that strictly use thehttps://scheme.-
Using the
secure_urlhelper:
This function generates a fully qualified URL to the given path using the HTTPS protocol.
php
$url = secure_url('user/profile');
// Result: https://example.com/user/profile -
Using the
assethelper (configuration):
If your application is configured correctly (e.g., behind a load balancer handling SSL), theasset()helper can automatically generate HTTPS links. However, to force it, you can configure theASSET_URLin.envor usesecure_asset('foo.css').
-
-
Question 15 of 20
Explain the concept of Controller Structures. How do Single Action Controllers (Invokable) differ from standard controllers?
Model answer
Controller Structures:
Controllers organize request handling logic. While standard controllers contain multiple methods (index, show, store, etc.) to handle various actions related to a resource, the framework supports different structures.Single Action (Invokable) Controllers:
Sometimes a controller is complex enough that it only needs to handle a single action. Instead of creating a class with one method namedindexorstore, you can define an__invokemethod.-
Creation:
bash
php artisan make:controller ProvisionServer --invokable -
Code Structure:
php
class ProvisionServer extends Controller
{
public function __invoke()
{
// Logic here
}
} -
Routing:
You do not need to specify the method name in the route.
php
Route::post('/server/provision', ProvisionServer::class);
Difference: Standard controllers group multiple related actions; Invokable controllers are dedicated to a single, specific task.
-
-
Question 16 of 20
How are Generation Shortcuts used in URL Generation? Give an example involving Controller Actions.
Model answer
Generation Shortcuts:
Instead of manually typing out full URL paths or relying solely on Named Routes, the framework provides shortcuts to generate URLs pointing directly to Controller Actions. This is useful because if the Route URI changes but the Controller method remains the same, the link remains valid.Action Helper:
Theactionhelper generates a URL for the given controller action.Syntax:
php
$url = action([UserController::class, 'profile'], ['id' => 1]);Explanation:
- The first argument is an array containing the Controller Class and the method name.
- The second argument is an array of route parameters (e.g., the user ID).
- This generates a URL like
http://example.com/user/profile/1assuming a route is defined for that controller action.
-
Question 17 of 20
Describe how to pass data from a Controller to a View using Blade Templates.
Model answer
Passing Data to Views:
Controllers usually retrieve data (e.g., from a database) and need to pass this data to the Blade View for rendering. There are several ways to achieve this.1. Using an Array:
Pass an associative array as the second argument to theviewhelper.
php
public function show()
{
return view('greeting', ['name' => 'James']);
}In Blade:
Hello, {{ $name }}2. Using the
withmethod:
Chain thewithmethod onto the view factory.
php
public function show()
{
return view('greeting')->with('name', 'James');
}3. Using
compact(PHP native):
If the variable names match the key names,compactis a clean shortcut.
php
public function show()
{
$name = 'James';
$age = 25;
return view('greeting', compact('name', 'age'));
} -
Question 18 of 20
Write a comprehensive note on Route Prefixing and Route Name Prefixing.
Model answer
Route Prefixing:
Theprefixmethod handles the URI structure. It groups routes that share a common path segment.- Example:
php
Route::prefix('admin')->group(function () {
Route::get('users', ...); // URL: /admin/users
});
Route Name Prefixing:
Thenamemethod (used on a group) handles the internal naming convention of routes. This is crucial for Named Routes. If you have a group of admin routes, you might want all their names to start withadmin..- Example:
php
Route::name('admin.')->group(function () {
Route::get('users', ...)->name('users');
});
// The full route name is 'admin.users'
// Usage: route('admin.users');
Combined Usage:
Often, both are used together for clarity in both the URL and the code:
php
Route::prefix('admin')->name('admin.')->group(function() { ... }); - Example:
-
Question 19 of 20
How does Blade handle Raw PHP? Why might a developer need to use the
@phpdirective?Model answer
Blade and Raw PHP:
While Blade provides convenient directives (like@if,@foreach) to avoid writing verbose PHP tags, there are situations where you might need to execute arbitrary PHP code within a view.The
@phpDirective:
Blade provides the@phpblock to execute a block of plain PHP code.Syntax:
blade
@php
$counter = 1;
$isActive = true;
// Any valid PHP code
@endphpUse Cases:
- Variable Assignment: Setting a variable or counter directly in the view (though usually, data should come from the controller).
- Data Manipulation: formatting a date or manipulating an array before display if a dedicated presenter/helper isn't available.
- Debugging: Quickly dumping a variable using
var_dumpordd()within the view.
-
Question 20 of 20
Derive the logic flow of a request in an MVC application utilizing Controller, Routing, and Blade components.
Model answer
The logic flow of a typical request follows these steps:
-
Request Entry: The user enters a URL (e.g.,
/products/5) in the browser. This request hits the application's entry point (index.php). -
Routing (Advanced Routing):
- The framework checks
routes/web.php. - It looks for a match:
Route::get('/products/{id}', [ProductController::class, 'show']);. - Parameter constraints (if any) are validated (e.g.,
idmust be numeric).
- The framework checks
-
Controller Dispatching:
- The router instantiates
ProductController. - It calls the
show($id)method, passing5as the argument. - Middleware attached to the route or controller is executed (e.g., checking if the user is logged in).
- The router instantiates
-
Processing (Controller):
- The
showmethod interacts with the Model to fetch product5from the database. - It prepares the data for the view.
- The
-
View Rendering (Blade):
- The controller returns
view('products.show', compact('product')). - Blade compiles the
products/show.blade.phptemplate (handling inheritance@extends, output{{ $product->name }}).
- The controller returns
-
Response: The compiled HTML is returned to the user's browser.
-
That's unit 3
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 3 of INT221 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 3 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.