Questions 11–30 | Beginner to Advanced
Focus: Laravel application structure, routing, middleware, controllers, Blade, validation, configuration, environment handling, migrations, and practical architecture.
Q11. What is the difference between routes/web.php and routes/api.php?
Interview Answer:
Laravel separates web-oriented and API-oriented routes so that applications can apply different middleware, state-management, and response conventions. Web routes normally support browser sessions, cookies, CSRF protection, and Blade responses. API routes are intended for stateless HTTP APIs and commonly return JSON.
Example:
Route::get('/products', [ProductController::class, 'index']);
For a browser page, the route may return a Blade view. For an API, the same business operation can return a JSON resource.
Scenario:
An e-commerce application has a customer website and a mobile application. Website routes can use session authentication and CSRF protection, while mobile/API routes can use token authentication. Keeping these concerns separated makes the application easier to reason about.
Interview follow-up:
Ask what middleware group each route uses in the Laravel version being discussed. Laravel's exact route bootstrap configuration can differ between major versions, so a strong answer should avoid assuming an old project structure.
Q12. What are named routes in Laravel and why are they useful?
Interview Answer:
A named route gives a route a stable application-level name. Instead of hard-coding URLs throughout the application, code can refer to the route by name.
Example:
Route::get('/products', [ProductController::class, 'index'])
->name('products.index');
Then:
return redirect()->route('products.index');
Blade:
<a href="{{ route('products.index') }}">Products</a>
Scenario:
If /products changes to /catalog/products, code using route('products.index') does not need to change. Only the route definition changes.
Named routes are particularly useful for redirects, links, forms, authorization logic, testing, and URL generation.
Q13. What are route parameters in Laravel?
Route parameters allow dynamic values to be captured from a URL.
Example:
Route::get('/products/{id}', function ($id) {
return $id;
});
For /products/25, id is 25.
Parameters can be constrained:
Route::get('/products/{id}', ...)->whereNumber('id');
Optional parameters can be written using ? when appropriate:
Route::get('/user/{name?}', ...);
Scenario:
An admin application may use /orders/{order} to identify an order. Route parameters are useful for resource-oriented URLs and become more powerful when combined with implicit model binding.
Q14. What is Laravel route model binding?
Route model binding lets Laravel resolve a route parameter into an Eloquent model.
Example:
Route::get('/products/{product}', [ProductController::class, 'show']);
Controller:
public function show(Product $product)
{
return $product;
}
Instead of manually doing Product::findOrFail($id), Laravel can resolve the model.
Scenario:
For /products/25, Laravel can retrieve Product 25 and automatically produce a not-found response when appropriate.
A developer should understand custom keys as well, such as binding by slug rather than numeric ID. This is useful for SEO-friendly URLs.
Interview follow-up:
Explain the difference between implicit and explicit binding and how scoped bindings work for nested resources.
Q15. What is middleware in Laravel?
Middleware is a layer that inspects or modifies an HTTP request before it reaches the application endpoint and can also process the outgoing response.
Conceptual flow:
Request -> Middleware -> Controller -> Response -> Middleware -> Client
Example:
public function handle($request, Closure $next)
{
if (!$request->user()) {
return redirect('/login');
}
return $next($request);
}
Common uses include authentication, authorization, rate limiting, logging, CORS, maintenance mode, and request normalization.
Scenario:
An /admin area can be protected with authentication and authorization middleware so that unauthenticated or unauthorized requests never reach the controller.
Q16. What is the difference between authentication and authorization in Laravel?
Authentication answers: "Who are you?"
Authorization answers: "Are you allowed to perform this action?"
Authentication may establish the current user through a session, token, or another mechanism.
Authorization can use gates or policies.
Example:
if ($user->can('update', $post)) {
// allow update
}
Scenario:
A support employee may be authenticated but still be forbidden from deleting financial records. Authentication identifies the employee; authorization determines whether deletion is permitted.
Interview tip:
Do not describe authentication and authorization as the same thing. This distinction is fundamental to secure application design.
Q17. What is a controller in Laravel and what should it contain?
A controller coordinates an HTTP request and application response. It should generally remain focused on request-level orchestration rather than becoming a giant business-logic class.
Example:
public function store(StoreProductRequest $request)
{
$product = $this->productService->create(
$request->validated()
);
return redirect()->route('products.show', $product);
}
Scenario:
If a controller contains validation, payment processing, inventory calculations, email delivery, reporting, and ten database queries, maintenance becomes difficult. Those responsibilities can be separated into requests, services, domain classes, jobs, and models where appropriate.
There is no universal requirement that every controller must call a service. Simple CRUD operations can remain simple. The goal is cohesive, maintainable code.
Q18. What is a resource controller in Laravel?
A resource controller provides conventional actions for CRUD-style resources.
Typical actions are:
index
create
store
show
edit
update
destroy
Example:
Route::resource('products', ProductController::class);
This can generate conventional routes such as:
GET /products
POST /products
GET /products/{product}
PUT/PATCH /products/{product}
DELETE /products/{product}
Scenario:
An admin product-management module maps naturally to resource routing.
Interview follow-up:
Explain when you would not use resource routing—for example, when an endpoint represents an operation rather than a conventional CRUD resource.
Q19. What is Blade in Laravel?
Blade is Laravel's templating engine. It provides a clean syntax for rendering dynamic HTML while allowing normal PHP when necessary.
Example:
<h1>{{ $product->name }}</h1>
Conditional:
@if($product->in_stock)
<span>Available</span>
@else
<span>Out of stock</span>
@endif
Blade also supports layouts, components, slots, loops, includes, and escaped output.
Scenario:
A product page can use a shared application layout and reusable product-card components rather than duplicating HTML across many views.
Q20. Why is {{ }} generally preferred over {!! !!} in Blade?
Blade's {{ }} syntax escapes output, helping protect against HTML injection and XSS when displaying untrusted content.
Example:
{{ $comment->body }}
Raw output:
{!! $html !!}
Raw output should only be used when the HTML is trusted or has been safely sanitized.
Scenario:
If a comment contains <script>...</script>, escaped rendering prevents the browser from treating the content as executable HTML.
Interview tip:
Never claim that Blade escaping makes an application automatically secure. Security depends on the complete data flow, validation, sanitization requirements, database usage, authentication, authorization, and frontend behavior.
Q21. What are Blade layouts and components?
Layouts provide a reusable page structure, while components encapsulate reusable UI pieces.
A layout may contain:
header
navigation
main content
footer
A component might represent:
button
alert
modal
product card
form field
Example component usage:
<x-product-card :product="$product" />
Scenario:
A SaaS dashboard may have one dashboard layout and dozens of reusable UI components. This reduces duplicated markup and makes UI changes safer.
Q22. What is Laravel validation and why should it be used?
Validation checks incoming data against application rules before business logic uses it.
Example:
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email'],
]);
For larger forms, a Form Request is often cleaner.
Validation protects data integrity and provides a predictable boundary between untrusted input and application logic.
Scenario:
An order endpoint should validate product IDs, quantities, shipping information, and payment-related fields before attempting to create an order.
Q23. What is a Form Request in Laravel?
A Form Request is a dedicated request class that can contain validation and authorization logic.
Example:
class StoreProductRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'price' => ['required', 'numeric', 'min:0'],
];
}
}
Controller:
public function store(StoreProductRequest $request)
{
$data = $request->validated();
}
Scenario:
As a project grows, moving validation out of controllers keeps controllers smaller and makes validation rules reusable and testable.
Q24. What is mass assignment in Eloquent?
Mass assignment allows multiple model attributes to be assigned from an array, for example:
Product::create([
'name' => $data['name'],
'price' => $data['price'],
]);
Laravel provides protection mechanisms so developers explicitly define which attributes may be mass assigned or otherwise control assignment behavior.
A common risk is accepting arbitrary request data:
Model::create($request->all());
Scenario:
If a users table contains an administrative flag, blindly accepting request data could allow a malicious client to submit fields that should never be user-controlled.
Interview tip:
Explain why validated data and explicit model assignment are important security boundaries.
Q25. What are migrations in Laravel?
Migrations are version-controlled definitions of database schema changes.
Example:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 10, 2);
$table->timestamps();
});
Commands:
php artisan make:migration create_products_table
php artisan migrate
Migrations allow a development team to reproduce schema changes consistently across environments.
Scenario:
When a team adds a sku column, the migration becomes part of source control and can be applied to development, staging, and production according to the deployment process.
Q26. What is the difference between migrate, rollback, refresh, and fresh?
migrate applies outstanding migrations.
rollback reverses the latest migration batch.
refresh rolls back migrations and runs them again.
fresh drops all tables and runs all migrations again.
These commands have very different safety implications.
Scenario:
During local development, fresh can be useful when rebuilding disposable data. Production environments require much more caution because destructive schema operations can cause data loss.
Interview tip:
Always explain commands in the context of environment safety rather than treating them as interchangeable.
Q27. What are seeders and factories in Laravel?
Seeders populate application data. Factories define repeatable ways to generate model data, commonly for testing and development.
Factory example:
User::factory()->count(50)->create();
Seeder example:
public function run(): void
{
User::factory()->count(20)->create();
}
Scenario:
A developer can create thousands of realistic test users, products, and orders to evaluate pagination, indexes, Eloquent relationships, and performance before production deployment.
Q28. How does Laravel configuration and .env work?
Laravel separates application configuration from environment-specific values.
Environment variables can include:
APP_ENV
APP_KEY
DB_HOST
DB_DATABASE
DB_USERNAME
DB_PASSWORD
CACHE_STORE
Configuration files access environment values and application code should generally read configuration through the config system.
Example:
config('app.name')
Scenario:
Development may use a local MySQL database while production uses a managed database service. The application code should not contain production credentials.
Important interview point:
Do not commit secrets to source control. Production configuration should be managed through an appropriate deployment/secrets process.
Q29. What is the Laravel service container and why does it matter for testing?
The service container resolves dependencies and can bind abstractions to implementations.
Example:
$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
A service can depend on:
public function __construct(PaymentGateway $gateway) {}
For tests, the binding can be replaced with a fake or mock implementation.
Scenario:
An order service normally charges a real payment gateway, but automated tests should not send real payments. Dependency injection allows the payment implementation to be substituted.
This is one reason dependency inversion and interface-based design can improve testability.
Q30. How should a Laravel application be structured as it grows?
There is no single architecture that is correct for every Laravel application. A small CRUD application can remain close to Laravel's conventional structure. A complex system may introduce service classes, actions, domain objects, DTOs, policies, jobs, repositories, or modules where they solve real complexity.
A practical flow can be:
Request
-> Controller
-> Service/Action
-> Eloquent or Repository
-> Database
-> Event/Job
-> Response
The key principle is separation of responsibilities.
Scenario:
An order workflow may need inventory reservation, payment authorization, order creation, event publishing, email, and asynchronous fulfillment. Keeping all of that inside one controller makes testing and maintenance difficult.
Interview-level answer:
Architecture should follow complexity. Do not add layers simply to appear "enterprise." Add an abstraction when it isolates a changing concern, improves testability, or makes the domain easier to understand.