Complete Laravel Interview Questions and Answers for Beginners to Experienced Developers
Laravel interviews are not only about remembering commands or syntax.
For an experienced Laravel developer, interviewers usually want to understand whether you know how Laravel works internally, how you structure applications, how you work with databases, APIs, queues, caching, security, authentication, and how you solve real-world performance problems.
In this complete Laravel interview guide, we will cover Laravel interview questions from basic to advanced level along with practical explanations and code examples.
Laravel Basic Interview Questions
1. What is Laravel?
Laravel is an open-source PHP web application framework used to build modern web applications and APIs.
It follows the MVC architectural pattern and provides many built-in features such as:
- Routing
- Eloquent ORM
- Authentication
- Authorization
- Validation
- Queues
- Events
- Caching
- Task scheduling
- Database migrations
- API development
Laravel reduces repetitive development work and provides a clean structure for building maintainable applications.
2. What does MVC mean in Laravel?
MVC stands for Model, View, and Controller.
- Model: Handles data and database operations.
- View: Handles the presentation layer or user interface.
- Controller: Handles incoming requests and communicates between models and views.
Example:
Route::get('/users', [UserController::class, 'index']);
The controller may retrieve users:
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
3. What are the main advantages of Laravel?
Some important Laravel advantages are:
- Clean MVC architecture
- Simple routing
- Eloquent ORM
- Built-in authentication and authorization support
- Database migrations
- Queues and background jobs
- Event-driven architecture
- Caching support
- Task scheduling
- Blade template engine
- REST API development
- Testing support
4. What is Artisan?
Artisan is Laravel's command-line interface.
It allows developers to execute many development and maintenance tasks from the terminal.
php artisan serve
php artisan migrate
php artisan make:model Product
php artisan make:controller ProductController
php artisan route:list
php artisan cache:clear
5. What is Composer and why is it required in Laravel?
Composer is a dependency manager for PHP.
Laravel uses Composer to install and manage packages required by the application.
composer install
composer update
composer require vendor/package
The application's dependencies are defined inside composer.json.
6. What is the .env file?
The .env file stores environment-specific configuration.
Examples include:
- Application environment
- Database credentials
- Mail configuration
- Cache configuration
- Queue configuration
- Third-party API credentials
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=
Sensitive production credentials should not normally be committed to a public Git repository.
7. What is APP_KEY in Laravel?
APP_KEY is used by Laravel's encryption services.
It can be generated using:
php artisan key:generate
The key should remain secret and should not be changed unnecessarily in a production application because encrypted data may depend on it.
8. Explain Laravel's folder structure.
Important Laravel directories include:
app/– application classesroutes/– routesresources/– Blade views and frontend resourcesdatabase/– migrations, seeders and factoriesconfig/– configuration filesstorage/– logs, generated files and application storagepublic/– publicly accessible filesvendor/– Composer dependencies
Laravel Routing Interview Questions
9. What is routing in Laravel?
Routing connects an incoming URL and HTTP method to application logic.
Route::get('/products', [ProductController::class, 'index']);
Route::post('/products', [ProductController::class, 'store']);
10. What is the difference between GET and POST routes?
GET requests are normally used to retrieve data.
POST requests are commonly used to submit or create data.
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
11. What are route parameters?
Route parameters allow dynamic values to be passed through URLs.
Route::get('/users/{id}', function ($id) {
return $id;
});
12. What is an optional route parameter?
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
The ? makes the parameter optional.
13. What are named routes?
Named routes allow developers to reference routes using a name instead of hardcoding URLs.
Route::get('/dashboard', [DashboardController::class, 'index'])
->name('dashboard');
Usage:
return redirect()->route('dashboard');
14. What is route model binding?
Route model binding automatically resolves a model from a route parameter.
Route::get('/users/{user}', function (User $user) {
return $user;
});
Laravel automatically retrieves the corresponding User model.
15. What is a resource route?
A resource route creates common CRUD routes automatically.
Route::resource('products', ProductController::class);
It creates routes for actions such as:
- index
- create
- store
- show
- edit
- update
- destroy
Controller Interview Questions
16. What is a controller?
A controller handles incoming HTTP requests and contains application request-handling logic.
class ProductController extends Controller
{
public function index()
{
return Product::all();
}
}
17. What is a resource controller?
A resource controller contains standard CRUD methods.
php artisan make:controller ProductController --resource
18. What is an invokable controller?
An invokable controller contains a single __invoke() method.
It is useful when a controller is responsible for only one action.
class GenerateReportController extends Controller
{
public function __invoke()
{
// Generate report
}
}
Blade Interview Questions
19. What is Blade?
Blade is Laravel's template engine.
It allows developers to write HTML with Laravel-specific directives.
@foreach ($users as $user)
{{ $user->name }}
@endforeach
20. What is the difference between {{ }} and {!! !!}?
{{ }} escapes HTML characters, helping prevent XSS attacks.
{!! !!} outputs raw HTML.
Raw output should only be used when the content is trusted and properly controlled.
21. What are @extends, @section and @yield?
They are commonly used for Blade layouts.
@extends('layouts.app')
@section('content')
<h1>Dashboard</h1>
@endsection
The layout might contain:
@yield('content')
Laravel Database and Migration Interview Questions
22. What are migrations?
Migrations are version-controlled database schema definitions.
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 10, 2);
$table->timestamps();
});
23. Why should we use migrations?
Migrations make database changes reproducible and easier to share across development, testing and production environments.
Instead of manually creating database tables on every server, developers can execute:
php artisan migrate
24. How do you roll back a migration?
php artisan migrate:rollback
You can also reset migrations:
php artisan migrate:reset
25. What are database seeders?
Seeders insert initial or sample data into the database.
php artisan make:seeder UserSeeder
Run seeders using:
php artisan db:seed
26. What are factories?
Factories generate sample model data, particularly useful during testing and development.
User::factory()->count(100)->create();
Eloquent ORM Interview Questions
27. What is Eloquent ORM?
Eloquent is Laravel's Object Relational Mapper.
It allows developers to work with database records through PHP model objects.
$users = User::where('status', 1)->get();
Instead of manually writing SQL:
SELECT * FROM users WHERE status = 1;
28. What is the difference between Eloquent and Query Builder?
Eloquent uses models and provides features such as relationships, accessors, scopes and model events.
Query Builder works more directly with database tables.
User::where('status', 1)->get();
Query Builder:
DB::table('users')
->where('status', 1)
->get();
Neither is always better. The choice depends on readability, application architecture and query complexity.
29. What is the difference between get() and first()?
get() returns a collection containing all matching records.
$users = User::where('status', 1)->get();
first() returns the first matching model or null.
$user = User::where('email', $email)->first();
30. What is the difference between find() and first()?
find() searches by the model's primary key.
$user = User::find(10);
first() returns the first result from a query.
$user = User::where('email', $email)->first();
31. What is findOrFail()?
findOrFail() retrieves a model by its primary key and throws a model-not-found exception when the record does not exist.
$user = User::findOrFail($id);
In an HTTP context, Laravel can translate this into a 404 response.
32. What is firstOrFail()?
$user = User::where('email', $email)->firstOrFail();
It returns the first matching record or throws an exception when no result exists.
33. What is pluck()?
pluck() retrieves the values of a particular column.
$names = User::pluck('name');
It can also return key-value pairs:
$users = User::pluck('name', 'id');
34. What is value()?
value() retrieves a single column value from the first matching record.
$email = User::where('id', 1)->value('email');
35. What is mass assignment?
Mass assignment means assigning multiple attributes to a model at once.
User::create([
'name' => 'John',
'email' => 'john@example.com',
]);
Laravel provides protection against unintended mass assignment.
36. What is $fillable?
$fillable specifies which model attributes may be mass assigned.
protected $fillable = [
'name',
'email'
];
37. What is $guarded?
$guarded specifies fields that should not be mass assigned.
protected $guarded = [
'id',
'is_admin'
];
38. What is an accessor?
An accessor transforms an attribute when it is retrieved.
For example, a developer may format a user's name before returning it.
39. What is a mutator?
A mutator transforms an attribute before it is stored.
For example, a developer may normalize or format data before saving it to the database.
40. What are model casts?
Casts convert model attributes into specific PHP types.
protected function casts(): array
{
return [
'is_active' => 'boolean',
'settings' => 'array',
'published_at' => 'datetime',
];
}
41. What is a local query scope?
A local scope allows commonly used query conditions to be reused.
public function scopeActive($query)
{
return $query->where('status', 1);
}
Usage:
$users = User::active()->get();
42. What are soft deletes?
Soft deletes mark records as deleted without permanently removing them.
The table uses a deleted_at column.
use SoftDeletes;
You can retrieve deleted records using:
User::withTrashed()->get();
Or restore them:
$user->restore();
Laravel Relationship Interview Questions
43. What are Eloquent relationships?
Eloquent relationships define associations between models.
Common relationships include:
- One to One
- One to Many
- Many to Many
- Has One Through
- Has Many Through
- Polymorphic relationships
44. Explain one-to-one relationship.
One record is associated with one other record.
Example: one user has one profile.
public function profile()
{
return $this->hasOne(Profile::class);
}
45. Explain one-to-many relationship.
One record can have multiple related records.
Example: one user has many posts.
public function posts()
{
return $this->hasMany(Post::class);
}
46. Explain many-to-many relationship.
Multiple records can be associated with multiple other records.
Example: users can have multiple roles and roles can belong to multiple users.
public function roles()
{
return $this->belongsToMany(Role::class);
}
47. What is a pivot table?
A pivot table stores relationships between two tables in a many-to-many relationship.
For example:
users
roles
role_user
The pivot table may contain:
user_id
role_id
48. What is attach()?
attach() adds a many-to-many relationship.
$user->roles()->attach($roleId);
49. What is detach()?
detach() removes a many-to-many relationship.
$user->roles()->detach($roleId);
50. What is sync()?
sync() synchronizes many-to-many relationships.
$user->roles()->sync([1, 2, 3]);
Existing relationships not included in the supplied array are normally removed.
Eager Loading and N+1 Interview Questions
51. What is lazy loading?
Lazy loading retrieves relationship data only when the relationship is accessed.
$user = User::first();
$posts = $user->posts;
52. What is eager loading?
Eager loading retrieves related data together with the main models.
$users = User::with('posts')->get();
This can significantly reduce the number of database queries.
53. What is the N+1 query problem?
The N+1 problem occurs when an application first executes one query to retrieve multiple records and then executes additional queries for each record's relationship.
Example:
$users = User::all();
foreach ($users as $user) {
echo $user->posts;
}
If 100 users are loaded, Laravel may execute one query for users and many more queries to fetch posts.
Use eager loading:
$users = User::with('posts')->get();
54. What is load()?
load() eager loads a relationship after a model has already been retrieved.
$user = User::find(1);
$user->load('posts');
55. What is withCount()?
withCount() retrieves the count of related records without loading all related models.
$users = User::withCount('posts')->get();
You can then access:
$user->posts_count
56. What is whereHas()?
whereHas() filters models based on conditions applied to a relationship.
$users = User::whereHas('posts', function ($query) {
$query->where('status', 'published');
})->get();
Middleware Interview Questions
57. What is middleware?
Middleware acts as a layer between an incoming HTTP request and application logic.
It can be used for:
- Authentication
- Authorization
- Role checking
- Request logging
- Rate limiting
- Language selection
58. Give a practical middleware example.
Suppose only administrators should access an admin dashboard.
public function handle($request, Closure $next)
{
if (!auth()->check() || auth()->user()->role !== 'admin') {
abort(403);
}
return $next($request);
}
Validation Interview Questions
59. How does validation work in Laravel?
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
]);
If validation fails during a normal web request, Laravel can redirect back with validation errors.
60. What is a Form Request?
A Form Request separates validation and authorization logic from controllers.
php artisan make:request StoreUserRequest
This keeps controllers cleaner and makes validation reusable.
Authentication and Authorization Interview Questions
61. What is authentication?
Authentication answers:
Who is the user?
For example, logging in using an email and password.
62. What is authorization?
Authorization answers:
What is this user allowed to do?
For example, whether the user can update or delete a particular post.
63. Authentication vs authorization?
Authentication verifies user identity.
Authorization checks permissions after the user's identity is known.
64. What are Gates?
Gates provide authorization rules.
Gate::define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
65. What are Policies?
Policies organize authorization rules around a specific model or resource.
For example:
PostPolicy
may contain:
- view
- create
- update
- delete
66. What is Laravel Sanctum?
Laravel Sanctum provides lightweight authentication mechanisms commonly used for API tokens and SPA authentication.
A common API token flow is:
Login
↓
Validate credentials
↓
Generate token
↓
Client sends token
↓
API verifies token
Service Container and Dependency Injection
67. What is Dependency Injection?
Dependency Injection means providing an object's required dependencies externally rather than creating those dependencies inside the class.
Example:
class OrderController extends Controller
{
public function __construct(
private OrderService $orderService
) {
}
}
Laravel's Service Container can automatically resolve many class dependencies.
Benefits include:
- Loose coupling
- Better testability
- Cleaner architecture
- Easier dependency replacement
68. What is the Service Container?
The Service Container manages class dependencies and dependency injection.
For example, an interface can be mapped to a concrete implementation:
$this->app->bind(
PaymentGatewayInterface::class,
RazorpayPaymentGateway::class
);
Now Laravel can inject the implementation wherever the interface is requested.
69. What is the difference between bind() and singleton()?
bind() can create a new instance when the dependency is resolved.
singleton() tells the container to reuse the same instance during the application's lifecycle.
70. What is a Service Provider?
Service Providers are responsible for registering and bootstrapping services used by the Laravel application.
They can register:
- Container bindings
- Third-party services
- Listeners
- Application services
71. What is the difference between register() and boot()?
register() is primarily used to register services and container bindings.
boot() is called after service providers have been registered and is commonly used for application bootstrapping that depends on registered services.
Facade Interview Questions
72. What is a Facade?
A Laravel Facade provides a convenient static-looking interface to an underlying service resolved by the Service Container.
Cache::get('users');
Log::info('User logged in');
DB::table('users')->get();
Events, Listeners and Observers
73. What is an Event?
An event represents something that happened inside the application.
Examples:
- UserRegistered
- OrderPlaced
- PaymentCompleted
74. What is a Listener?
A listener responds to an event.
Example:
OrderPlaced
↓
SendOrderConfirmation
↓
UpdateInventory
↓
NotifyAdmin
Using events helps separate unrelated responsibilities.
75. What is an Observer?
An Observer listens to Eloquent model lifecycle events.
Examples include:
- creating
- created
- updating
- updated
- deleting
- deleted
76. Observer vs Event Listener?
Observers are primarily designed around model lifecycle events.
Application events and listeners can represent broader domain or application events.
For example:
Product updated → Observer
Payment completed → Application Event
Laravel Queue and Job Interview Questions
77. What is a queue?
A queue allows long-running tasks to be processed asynchronously instead of making the user wait for the task to complete during the HTTP request.
Examples:
- Sending emails
- Generating PDFs
- Importing large files
- Processing images
- Sending notifications
- Generating reports
78. What is a Job?
A Job represents a task that can be dispatched for processing.
php artisan make:job SendInvoiceEmail
Dispatch:
SendInvoiceEmail::dispatch($invoice);
79. Why should email sending be moved to a queue?
Sending email can involve communication with an external mail server.
If it happens during the user's request, it can make the response slower.
A better approach is:
User places order
↓
Order saved
↓
Email job dispatched
↓
User receives response
↓
Queue worker sends email
80. How do you process queued jobs?
A queue worker is used to process pending jobs.
php artisan queue:work
81. What happens when a queued job fails?
Failed jobs can be recorded, logged and retried depending on the application's queue configuration.
Developers should also handle:
- Exceptions
- Retry attempts
- Timeouts
- Permanent failures
Task Scheduler Interview Questions
82. What is Laravel Task Scheduling?
The scheduler provides a clean way to define recurring commands and jobs inside the Laravel application.
Example:
Schedule::command('reports:daily')->daily();
Common use cases include:
- Daily reports
- Subscription renewal checks
- Expiry notifications
- Cleaning temporary files
- Database backups
83. What is the difference between Laravel Scheduler and Cron?
Cron is the operating system's scheduler.
Laravel Scheduler allows scheduling rules to be managed inside Laravel code.
Usually, the server cron runs Laravel's scheduler regularly, and Laravel determines which scheduled tasks should execute.
Cache and Redis Interview Questions
84. What is caching?
Caching stores frequently requested or expensive-to-calculate data temporarily so that the application can reuse it.
$users = Cache::remember('active_users', 600, function () {
return User::where('status', 1)->get();
});
85. Why does caching improve performance?
Without caching:
Request
↓
Database query
↓
Process result
↓
Response
With caching:
Request
↓
Cache
↓
Response
This can reduce database workload.
86. What is Redis?
Redis is an in-memory data store commonly used with Laravel for:
- Caching
- Queues
- Sessions
- Counters
- Temporary application data
87. What is cache invalidation?
Cache invalidation means removing or updating cached data when the original data changes.
For example:
Product::create($data);
Cache::forget('products');
API Interview Questions
88. What is a REST API?
A REST API allows applications to communicate using HTTP requests.
Common HTTP methods include:
- GET – Retrieve
- POST – Create
- PUT/PATCH – Update
- DELETE – Delete
89. What is an API Resource?
An API Resource transforms a model into a controlled JSON representation.
return new UserResource($user);
This helps prevent exposing unnecessary database fields.
90. Why should you not return your entire model directly from every API?
Returning models directly may expose fields that clients do not need.
API Resources provide better control over:
- Response fields
- Formatting
- Nested data
- Consistency
91. What HTTP status codes should Laravel API developers know?
- 200: Successful request
- 201: Resource created
- 204: Success without response body
- 400: Bad request
- 401: Unauthenticated
- 403: Forbidden
- 404: Not found
- 422: Validation/unprocessable request
- 500: Server error
92. What is API rate limiting?
Rate limiting restricts how many requests a client can make during a particular period.
It helps protect applications from:
- Abuse
- Accidental request loops
- Excessive API usage
- Some denial-of-service patterns
Database Transaction Questions
93. What is a database transaction?
A transaction groups multiple database operations so they either succeed together or fail together.
DB::transaction(function () {
$order = Order::create([
'user_id' => auth()->id()
]);
Payment::create([
'order_id' => $order->id,
'amount' => 1000
]);
});
94. Where should transactions be used?
Transactions are useful when multiple database changes belong to one logical operation.
Examples include:
- Creating order and order items
- Payment processing
- Stock updates
- Banking-like balance transfers
- Invoice creation with related entries
Laravel Security Interview Questions
95. How does Laravel protect against CSRF?
Laravel provides CSRF protection for state-changing web requests.
Blade forms commonly include:
@csrf
This generates a token that Laravel validates.
96. What is SQL Injection?
SQL Injection occurs when unsafe user input is inserted directly into SQL statements.
Laravel's Eloquent and Query Builder use parameter binding for normal queries, which helps prevent SQL injection.
Developers still need to be careful with raw SQL.
97. What is XSS?
Cross-Site Scripting occurs when malicious scripts are injected into content displayed to other users.
Blade's escaped output helps reduce this risk:
{{ $userInput }}
98. How are passwords stored securely?
Passwords should be hashed using Laravel's hashing facilities rather than stored as plain text.
Hash::make($request->password);
Laravel Performance Interview Questions
99. How can you improve Laravel application performance?
Performance optimization should begin by identifying the actual bottleneck.
Common improvements include:
- Avoid N+1 queries
- Use eager loading
- Add proper database indexes
- Select only required columns
- Use pagination
- Use caching
- Move heavy operations to queues
- Use Redis when appropriate
- Analyze slow queries
- Optimize images and frontend assets
- Use production caches
100. Why should we avoid SELECT * for large queries?
If only three columns are needed, retrieving every column wastes memory, bandwidth and database resources.
Instead of:
User::all();
Use:
User::select('id', 'name', 'email')->get();
101. Why are database indexes important?
Indexes help the database locate records more efficiently.
Columns commonly considered for indexes include fields frequently used in:
- WHERE conditions
- JOIN conditions
- ORDER BY
- Foreign-key lookups
However, unnecessary indexes can increase storage and write overhead, so they should be chosen based on query patterns.
102. How do you find slow database queries?
Useful approaches include:
- Inspect query logs
- Use database slow-query logging
- Use Laravel debugging/profiling tools in suitable environments
- Analyze SQL with EXPLAIN
- Check number of queries
- Look for queries executed inside loops
Large Dataset Interview Questions
103. How would you handle 500,000 records in Laravel?
The first rule is to avoid loading all 500,000 records into memory unless absolutely required.
Bad approach:
$users = User::all();
Better techniques include:
- Pagination
- Cursor pagination
- Chunking
- Lazy collections
- Database indexing
- Selecting required columns only
- Queues for background processing
- Caching
104. What is chunk()?
chunk() processes records in smaller batches.
User::chunk(1000, function ($users) {
foreach ($users as $user) {
// Process
}
});
This avoids loading the entire dataset into memory at once.
105. What is chunkById()?
chunkById() processes records in batches based on their IDs.
It is particularly useful when records may be updated while processing.
User::chunkById(1000, function ($users) {
foreach ($users as $user) {
// Process
}
});
106. What is cursor()?
cursor() allows models to be iterated lazily instead of loading the complete result set into memory.
foreach (User::cursor() as $user) {
// Process user
}
107. What is lazy()?
lazy() returns a lazy collection while retrieving records in chunks internally.
User::lazy()->each(function ($user) {
// Process
});
108. chunk() vs cursor() vs lazy()?
chunk(): Retrieves batches and passes each batch to a callback.
cursor(): Provides lazy iteration over records and can keep memory usage low.
lazy(): Provides a LazyCollection interface while loading data in manageable batches.
The best option depends on whether you need batch operations, model processing, memory efficiency, and whether records may change during processing.
Pagination Interview Questions
109. What is paginate()?
User::paginate(20);
It provides records together with pagination metadata, including total page information.
110. What is simplePaginate()?
User::simplePaginate(20);
It avoids calculating total page counts and provides simpler previous/next navigation.
111. What is cursorPaginate()?
User::orderBy('id')->cursorPaginate(20);
Cursor pagination uses a cursor rather than traditional offset-based pagination.
It can provide better performance for very large ordered datasets.
112. paginate() vs cursorPaginate()?
paginate() is convenient when users need page numbers and total counts.
cursorPaginate() is useful for large datasets and next/previous style navigation where numbered pages are not required.
File Storage Interview Questions
113. How does Laravel file storage work?
Laravel provides a filesystem abstraction for working with local storage and cloud storage services.
Storage::disk('public')->put($path, $content);
114. What does php artisan storage:link do?
It creates a symbolic link that allows files stored in the public storage disk to be accessible from the application's public directory.
php artisan storage:link
Mail and Notification Interview Questions
115. What is a Mailable?
A Mailable represents an email in Laravel.
php artisan make:mail OrderInvoiceMail
116. What is Laravel Notification?
Notifications provide a unified way to send messages through multiple channels.
Depending on configuration and available channels, notifications can be used for email, database notifications and other delivery mechanisms.
Testing Interview Questions
117. What is the difference between Unit and Feature tests?
A Unit test normally tests a small isolated piece of logic.
A Feature test may test a larger application flow such as:
HTTP request
↓
Route
↓
Controller
↓
Database
↓
Response
118. How can you test an API endpoint?
Laravel provides HTTP testing helpers.
$response = $this->getJson('/api/users');
$response->assertStatus(200);
Laravel Architecture Interview Questions
119. What is the Repository Pattern?
The Repository Pattern introduces a layer between business logic and data access.
For example:
Controller
↓
Service
↓
Repository
↓
Model/Database
It can be useful in larger applications when it provides meaningful separation, but it should not be added automatically if it only introduces unnecessary abstraction.
120. What is a Service Layer?
A Service Layer stores business logic outside controllers.
Instead of putting payment logic directly inside a controller:
PaymentController
↓
PaymentService
↓
Payment Gateway
This can make controllers smaller and business logic easier to reuse and test.
Real-World Laravel Scenario Interview Questions
121. Your Laravel application works fast with 1,000 records but becomes slow with 500,000. What would you do?
I would first identify the bottleneck instead of assuming Laravel itself is slow.
I would check:
- Number of SQL queries
- N+1 queries
- Slow SQL queries
- Database indexes
- Large SELECT operations
- Pagination strategy
- Memory usage
- Repeated queries
- API response size
- Heavy synchronous operations
Then I would optimize the specific problem using indexing, eager loading, caching, pagination, queues, chunking or query restructuring.
122. You need to send emails to 10,000 users. What would you do?
I would not send all emails inside a normal HTTP request.
A better architecture is:
Request
↓
Create campaign
↓
Dispatch jobs
↓
Return response
↓
Queue workers process emails
I would also consider rate limits, retries, failed jobs and the mail provider's sending limits.
123. You need to import 5 lakh Excel rows. What would you do?
I would avoid parsing and inserting the complete file inside one HTTP request.
A scalable approach could include:
- Upload the file
- Store an import record
- Process the file asynchronously
- Read the file in chunks
- Validate data in manageable batches
- Use batch inserts when appropriate
- Track success and failure counts
- Store import errors
124. How would you prevent duplicate order creation?
Possible techniques include:
- Database unique constraints
- Idempotency keys for APIs
- Transactions
- Careful request state management
The database should generally enforce important uniqueness rules where possible rather than relying only on application-level checks.
125. How would you implement payment gateway integration?
A typical payment flow can be:
Create order
↓
Store pending payment
↓
Generate gateway request
↓
Customer completes payment
↓
Gateway redirects/webhook fires
↓
Verify payment with gateway
↓
Update payment status
↓
Confirm order
Important considerations include:
- Never trust only frontend success responses
- Verify transaction details server-side
- Use database transactions when appropriate
- Handle duplicate callbacks
- Store gateway transaction IDs
- Log failures securely
126. What happens if a payment webhook comes twice?
The webhook handler should be idempotent.
For example, before marking a payment successful, check whether that gateway transaction has already been processed.
A unique database constraint can provide another layer of protection.
127. How would you handle stock when two users purchase the last item simultaneously?
This is a concurrency problem.
Depending on the application, techniques may include:
- Database transactions
- Row locking
- Atomic updates
- Database constraints
The goal is to prevent both requests from successfully consuming the same final inventory quantity.
128. Your API is slow. What would you check?
I would inspect:
- SQL query count
- N+1 relationships
- Response payload size
- External API calls
- Database indexes
- Serialization overhead
- Cache opportunities
- Server resources
- Network latency
129. When should you use a queue?
A queue is useful when a task does not need to complete before the user receives the response.
Examples:
- Email sending
- Report generation
- Notifications
- Large imports
- Image processing
- Third-party synchronization
130. When should you use caching?
Caching is useful when data is frequently requested but does not change on every request.
Good examples include:
- Configuration-like database data
- Dashboard statistics
- Popular product lists
- Frequently requested API data
Developers must also plan how cached data will be invalidated.
Common Laravel Interview Rapid-Fire Questions
131. What does dd() do?
dd() means dump and die. It displays a value and stops execution.
132. What does dump() do?
dump() displays a value without necessarily stopping execution.
133. What is redirect()->back()?
It redirects the user to the previous URL.
134. What is old()?
old() retrieves flashed input from a previous request, commonly after validation failure.
135. What does compact() do?
It is a PHP function that creates an array using variable names.
return view('users.index', compact('users'));
136. What is firstOrCreate()?
It searches for a record and creates one if it does not exist.
User::firstOrCreate(
['email' => $email],
['name' => $name]
);
137. What is updateOrCreate()?
It updates a matching record or creates a new one.
User::updateOrCreate(
['email' => $email],
['name' => $name]
);
138. What is exists()?
It checks whether matching records exist.
$exists = User::where('email', $email)->exists();
139. What is count()?
It returns the number of matching records.
$count = User::where('status', 1)->count();
140. What is latest()?
latest() orders query results by a timestamp column, commonly created_at, in descending order.
Post::latest()->get();
141. What is oldest()?
oldest() orders results in ascending timestamp order.
142. What is when()?
when() helps conditionally modify a query.
User::query()
->when($request->status, function ($query, $status) {
$query->where('status', $status);
})
->get();
143. What is DB::raw()?
DB::raw() allows raw SQL expressions to be included in queries.
Raw expressions should be used carefully, especially when user-provided values are involved.
144. What is a trait in PHP/Laravel?
A trait is a PHP language feature used to reuse methods across multiple classes.
145. What are Laravel helpers?
Laravel provides helper functions for common tasks.
Examples include:
route()
url()
asset()
config()
env()
view()
redirect()
response()
Important Laravel Interview Topics for Experienced Developers
If you have around 3–5 years of Laravel experience, make sure you can explain these topics clearly:
- MVC architecture
- Laravel request lifecycle
- Routing
- Middleware
- Form Request validation
- Eloquent ORM
- Query Builder
- Relationships
- Eager loading
- N+1 query problem
- Database migrations
- Database transactions
- Service Container
- Dependency Injection
- Service Providers
- Facades
- Events and Listeners
- Observers
- Queues and Jobs
- Task Scheduler
- Caching
- Redis
- Authentication
- Authorization
- Gates and Policies
- Sanctum
- REST APIs
- API Resources
- File storage
- Security
- Database indexing
- Query optimization
- Large dataset processing
- Pagination
- Testing
- Deployment and production optimization
How Should You Answer Laravel Interview Questions?
For experienced developer interviews, avoid giving only one-line definitions.
A strong answer generally follows this structure:
Definition
↓
Why it is used
↓
How it works
↓
Code example
↓
Real project example
For example, if the interviewer asks:
What is a queue?
Instead of saying:
"A queue runs background tasks."
You can explain:
"Laravel queues are used to move time-consuming tasks outside the main HTTP request. For example, in an e-commerce application, after an order is created I can immediately return the order confirmation to the customer and dispatch an email job to a queue. A queue worker later processes that email. This improves response time and also allows retries if sending fails."
This type of answer demonstrates practical experience instead of only theoretical knowledge.
Final Thoughts
Laravel interviews for experienced developers usually go beyond framework syntax.
Interviewers want to know whether you understand how to design maintainable applications, optimize database queries, handle large datasets, build secure APIs, use queues, manage transactions, implement authentication and authorization, and troubleshoot real production problems.
The best preparation method is not simply memorizing answers.
Build small examples and understand why Laravel provides each feature.
When you understand the reason behind Eloquent relationships, dependency injection, queues, caching, transactions, indexes, middleware, events and APIs, answering Laravel interview questions becomes much easier.
Keep practicing these concepts with real Laravel projects and scenario-based problems to improve your confidence for your next Laravel developer interview.
Discussion
Questions and notes from readers. Comments appear after a short review.
No comments yet. Start the discussion.