Part 1: Laravel Core Concepts
1. What is the Lifecycle of a Laravel Application?
The request lifecycle defines how Laravel processes an incoming browser request and sends back a response:
-
Entry Point: Every request enters through
public/index.php. -
Autoloading: Composer’s autoloader (
vendor/autoload.php) is loaded. -
Application Bootstrap:
bootstrap/app.phpinitializes the Laravel Application container and HTTP Kernel. -
HTTP Kernel: The HTTP Kernel executes bootstrappers (loads configuration, environment variables, error handling, and registers Service Providers).
-
Service Providers: Laravel iterates through all registered Service Providers, calling their
register()methods first, followed by theirboot()methods. -
Middleware & Routing: The request passes through global middleware and is dispatched by the Router through route-specific middleware.
-
Controller Action / Closure: The matching route controller method executes and returns a response.
-
HTTP Response: The response passes back through the middleware pipeline and is sent to the client’s browser.
-
Termination: The kernel calls the
terminate()method on any middleware implementing it to handle cleanup.
2. What is a Service Container and a Service Provider?
-
Service Container: An Inversion of Control (IoC) container used to manage class dependencies and perform dependency injection automatically across the application.
-
Service Provider: The central place to configure and register bindings, event listeners, middleware, and routes into the Service Container.
-
register(): Used only to bind things into the Service Container. -
boot(): Executed after all service providers are registered; safe to call registered services here.
-
3. What is a Facade in Laravel?
A Facade provides a static-like interface to classes registered inside the Service Container. Under the hood, it uses the magic method __callStatic() to resolve underlying service instances dynamic from the container.
-
Example:
Cache::get('key')resolves thecacheservice from the container and callsget('key')on it.
4. What are Middleware, Gate, and Policy? (With Examples)
Middleware
Code executed before or after a request reaches a controller. Used for request filtering and modification.
-
Real-World Example: Checking if a user is an active subscriber or an admin before allowing access to
/dashboard.
public function handle(Request $request, Closure $next) {
if (! $request->user()->isAdmin()) {
return redirect('/home');
}
return $next($request);
}
Gate
A simple, closure-based approach to checking user permissions for a specific action that is not necessarily bound to a specific model.
-
Real-World Example: Checking if a user can access a debug panel.
// In AppServiceProvider
Gate::define('view-debug-panel', function (User $user) {
return $user->is_developer === true;
});
// Usage in Controller
if (Gate::allows('view-debug-panel')) { ... }
Policy
Class-based authorization logic organized around a specific Eloquent Model.
-
Real-World Example: Checking if a user can update or delete a specific
Post.
// PostPolicy.php
public function update(User $user, Post $post) {
return $user->id === $post->user_id;
}
// Usage in Controller
$this->authorize('update', $post);
5. What are Eager Loading, Lazy Loading, and the N+1 Query Problem?
N+1 Query Problem
Occurs when code executes 1 initial query to get $N$ parent records, and then runs $N$ separate queries inside a loop to fetch related records—resulting in $N + 1$ database queries.
// 1 query to get 100 books
$books = Book::all();
foreach ($books as $book) {
// 100 queries to get author for each book! (Total: 101 queries)
echo $book->author->name;
}
Eager Loading
Pre-fetches related models upfront using the with() method, solving the N+1 query problem by reducing the total queries to just 2.
// Executes only 2 queries regardless of count
$books = Book::with('author')->get();
Lazy Loading
Loading relationships on-demand only when accessed on the model instance (e.g., $book->author). Useful if you only need the relationship conditionally.
6. Frequently Used Artisan Commands During Development
# Server & Code Generation
php artisan serve
php artisan make:controller ItemController --resource
php artisan make:model Item -mcr # Model, Migration, Controller, Resource
php artisan make:middleware CheckRole
php artisan make:policy PostPolicy --model=Post
# Database Operations
php artisan migrate
php artisan migrate:fresh --seed
php artisan db:seed
# Clearing Cache during configuration updates
php artisan config:clear
php artisan route:clear
php artisan cache:clear
# Inspection & Maintenance
php artisan route:list
php artisan tinker
Part 2: PHP & Composer Standards
1. What is Composer?
Composer is the standard dependency manager for PHP. It allows developers to declare, install, and update external libraries required by a PHP project, managing versioning and autoloading automatically via composer.json and composer.lock.
2. What is composer dump-autoload?
This command regenerates the autoloader classmap (vendor/composer/autoload_classmap.php). You run it when you add new classes or helper files to your project without creating a new package or updating composer.json, forcing Composer to index the files immediately.
3. What is PSR-4, and How Does It Differ From PSR-3?
-
PSR-4 (Autoloading Standard): Standardizes mapping PHP namespaces directly to file system directory paths, enabling class files to auto-load without manual
requireorincludestatements. -
PSR-3 (Logger Interface): Standardizes logging interfaces across PHP applications, defining common methods like
emergency(),alert(),error(),warning(),info(), anddebug().
Key Difference: PSR-4 handles code loading, while PSR-3 standardizes logging interfaces.
4. What is a Trait in PHP?
A Trait is a mechanism for code reuse in single-inheritance languages like PHP. It allows developers to reuse sets of methods horizontally across independent classes.
trait Loggable {
public function log($message) {
echo "Log: " . $message;
}
}
class User {
use Loggable;
}
5. Types of Errors in PHP
-
Fatal Errors (
E_ERROR): Critical runtime errors that immediately halt script execution (e.g., instantiating a non-existent class). -
Parse/Syntax Errors (
E_PARSE): Occur at compile time due to invalid PHP syntax (e.g., missing semicolon). -
Warning Errors (
E_WARNING): Non-fatal errors; execution continues (e.g., callinginclude()on a non-existent file). -
Notice Errors (
E_NOTICE): Minor issues that do not break execution (e.g., accessing an undefined variable). -
Deprecated Errors (
E_DEPRECATED): Warnings indicating a function or feature will be removed in future PHP versions.
6. What is an Exception in PHP? (With Real Example)
An Exception is an object representing an unexpected condition or runtime error that can be gracefully intercepted using a try-catch block, preventing script failure.
Real-World Example: Processing Payment
try {
$payment->charge($amount);
} catch (InsufficientFundsException $e) {
Log::error('Payment failed: ' . $e->getMessage());
return response()->json(['error' => 'Your balance is too low.'], 400);
} catch (\Exception $e) {
return response()->json(['error' => 'System error occurred.'], 500);
}
Part 3: Architecture Patterns & SOLID Principles
1. What is the SOLID Principle?
| Principle | Meaning | Quick Explanation |
| S | Single Responsibility | A class should have one, and only one, reason to change. |
| O | Open/Closed | Classes should be open for extension, but closed for modification. |
| L | Liskov Substitution | Subclasses should be substitutable for their base classes without breaking app logic. |
| I | Interface Segregation | Prefer many small, specific interfaces over one large, monolithic interface. |
| D | Dependency Inversion | High-level modules should depend on abstractions (interfaces), not concrete implementations. |
2. What is the Repository Pattern?
The Repository Pattern serves as an abstraction layer between the business logic layer (Controller/Services) and the data access layer (Eloquent DB).
Benefits:
-
Keeps controllers clean and decouples application logic from database ORM dependencies.
-
Makes unit testing easy by allowing developers to mock repositories without running actual database queries.
Part 4: Database Queries & Joins
1. How to Find the 4th Highest Salary of an Employee
Using Standard SQL (LIMIT & OFFSET):
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 3;
Using Window Functions (ANSI SQL Standard):
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as salary_rank
FROM employees
) AS ranked_salaries
WHERE salary_rank = 4;
2. Types of SQL Joins
-
INNER JOIN: Returns records that have matching values in both tables.
-
LEFT (OUTER) JOIN: Returns all records from the left table and matched records from the right table (unmatched right rows return
NULL). -
RIGHT (OUTER) JOIN: Returns all records from the right table and matched records from the left table.
-
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table.
-
CROSS JOIN: Produces a Cartesian product combining every row from the first table with every row from the second table.
-
SELF JOIN: Joins a table to itself to compare rows within the same table.
Bonus: Frequently Asked Interview Questions
1. What is the difference between interface and abstract class in PHP?
-
Interface: Defines a contract of public method signatures that a class must implement. Cannot contain state/properties or concrete method implementations (prior to PHP 8 traits). Supports multiple inheritance (
implements InterfaceA, InterfaceB). -
Abstract Class: Serves as a base class that can contain implemented methods, properties, and access modifiers. A class can only extend one abstract class.
2. What is Method Injection vs Constructor Injection?
-
Constructor Injection: Class dependencies are passed via
__construct(). Preferred when the dependency is required throughout the entire object lifecycle. -
Method Injection: Passing a dependency directly into a specific method signature (e.g., type-hinting
Request $requestinside a Laravel controller method).