The Ultimate Laravel Interview Guide: 100+ Questions for Beginners to Experts
Preparing for a Laravel developer role? This comprehensive guide is your secret weapon. We've compiled over 100 of the most competitive Laravel interview questions, categorized by role and complexity—from foundational knowledge for beginners to deep architectural puzzles for experts. Each question is designed to test not just memorization, but real-world understanding, problem-solving skills, and coding prowess.
Let's dive in!
Table of Contents
Beginner Level Questions <a name="beginner"></a>
Focus: Basic understanding, core concepts, and simple implementations.
Core & MVC Architecture
What is Laravel, and what are its main advantages over other PHP frameworks?
(Tests basic market awareness)Explain the MVC architecture. How does Laravel implement it?
Model: Represents the data and business logic (e.g., an
App\Models\User
class).View: Presents the data to the user (Blade templates).
Controller: Handles user requests, interacts with the Model, and returns a View/Response.
What is the purpose of the
artisan
command-line tool? Give three examples of commonartisan
commands.Example:
php artisan make:model Product -mcr
(creates a Model, Migration, and Controller).
What are Service Providers? Name one core service provider that Laravel uses by default.
(Looks for knowledge of bootstrapping. Answer:RouteServiceProvider
,AppServiceProvider
)
Routing & Basic Controllers
How do you define a basic GET route that returns a view?
// routes/web.php Route::get('/welcome', function () { return view('welcome'); });
What is the difference between
Route::get()
andRoute::post()
?
(Tests understanding of HTTP verbs)How do you pass a URL parameter (e.g., an
id
) to a route and access it in a controller?Route::get('/user/{id}', [UserController::class, 'show']); // In UserController public function show($id) { ... }
Blade Templating
How do you display a PHP variable
$name
in a Blade template?{{ $name }}
What is the Blade directive for including a sub-view?
@include('partials.header')
How do you create a loop in Blade to display an array of
$products
?@foreach($products as $product) <p>{{ $product->name }}</p> @endforeach
Basics of Eloquent ORM
What is Eloquent? What is an Eloquent Model?
(Object-Relational Mapper that allows interacting with databases using an object-oriented syntax)How do you retrieve all records from a
posts
table using Eloquent? Assume the model isPost
.$posts = Post::all();
How do you retrieve a single record by its primary key?
$post = Post::find(1);
What is the naming convention for Eloquent model names and database table names?
Model:
Post
(Singular, PascalCase)Table:
posts
(Plural, snake_case)
Migrations & Databases
What are migrations? What problem do they solve?
(Version control for your database schema.)How do you create a new migration file to create a
products
table?php artisan make:migration create_products_table
Write a migration to add a
title
(string) anddescription
(text) column to a table.public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description'); $table->timestamps(); }); }
How do you run all pending migrations?
php artisan migrate
Basic Validation
How would you validate that a
email
field is required and formatted correctly in a Laravel controller?$validated = $request->validate([ 'email' => 'required|email', ]);
Security Basics
What is CSRF protection, and how does Laravel enable it by default for web forms?
Answer: Laravel automatically generates a CSRF token for each active user session. You must include
@csrf
in your forms.
Intermediate Level Questions <a name="intermediate"></a>
Focus: Deeper understanding of components, real-world scenarios, and application architecture.
Advanced Eloquent & Relationships
Explain the different types of Eloquent relationships.
(HasOne, HasMany, BelongsTo, BelongsToMany, ManyToMany)Scenario: A
User
hasMany
Post
s. How would you define this relationship in the User model? How would you eager load a user's posts to avoid the N+1 query problem?// In User.php model public function posts() { return $this->hasMany(Post::class); } // Eager Loading $users = User::with('posts')->get();
What are Eloquent Accessors and Mutators? Write an example of a accessor for a
first_name
field that always capitalizes the first letter.public function getFirstNameAttribute($value) { return ucfirst($value); }
What is query scoping? Create a local scope to get only
active
products.// In Product.php model public function scopeActive($query) { return $query->where('is_active', true); } // Usage: Product::active()->get();
What is the difference between
$fillable
and$guarded
properties in an Eloquent model?$fillable
: Whitelist of attributes that are mass assignable.$guarded
: Blacklist of attributes that are not mass assignable.
Advanced Routing & Middleware
What is Middleware? Give two examples of built-in Laravel middleware.
(Answer:auth
,throttle
,web
,api
)How do you create a custom middleware to check if a user is an admin? What are the steps?
Create:
php artisan make:middleware IsAdmin
Implement logic in
handle
method.Register it in
app/Http/Kernel.php
.Attach it to a route.
What are Route Groups? How would you apply the
auth
middleware to a group of routes and prefix them with/admin
?Route::prefix('admin')->middleware('auth')->group(function () { Route::get('/dashboard', 'AdminController@dashboard'); });
What is Route Model Binding? Show implicit and explicit binding.
Implicit:
Route::get('/user/{user}', ...);
->public function show(User $user)
Explicit: Defining custom logic in
RouteServiceProvider::boot()
.
Service Container & Dependency Injection
What is the Laravel Service Container?
(A powerful tool for managing class dependencies and performing dependency injection.)What is Dependency Injection? Show an example of Constructor Injection in a Laravel controller.
public function __construct(UserRepository $users) { $this->users = $users; }
What are Facades? How do they work under the hood?
(Facades provide a "static" interface to classes registered in the service container. They proxy calls to the underlying object via the__callStatic()
magic method.)
Forms & Requests
What are Form Requests and why are they useful?
(Custom request classes that handle authorization and validation logic, keeping controllers clean.)How do you handle file uploads in Laravel? Store an uploaded
avatar
image in thestorage/app/public
directory and make sure it's accessible from the web.$path = $request->file('avatar')->store('avatars', 'public'); // Don't forget to run `php artisan storage:link`
API Development (Laravel Sanctum/Passport)
How would you create a simple API endpoint that returns a list of products as JSON?
Route::get('/api/products', function () { return response()->json(Product::all()); });
What is the difference between Laravel Sanctum and Laravel Passport? When would you use one over the other?
Sanctum: Lightweight, for SPAs, mobile apps, and simple token-based APIs.
Passport: Full OAuth2 server implementation, for complex API ecosystems.
Testing
What are the two main types of tests in Laravel?
(Unit tests and Feature tests.)Write a basic feature test to ensure the
/home
route returns a 200 status code for an authenticated user.public function test_home_route_for_authenticated_user() { $user = User::factory()->create(); $this->actingAs($user) ->get('/home') ->assertStatus(200); }
Performance & Debugging
What is the N+1 query problem? How do you identify and fix it in Laravel?
Identify: Use Laravel Debugbar or
DB::listen
.Fix: Use eager loading (
with()
).
What is Laravel Caching? How would you cache the result of an expensive database query for 24 hours?
$products = Cache::remember('all-products', 60 * 24, function () { return Product::all(); });
Expert Level Questions <a name="expert"></a>
Focus: System design, deep internals, performance optimization, and security hardening.
Advanced Architecture & Patterns
Explain the Repository Pattern. What are its benefits, and how would you implement it in Laravel?
(Abstracts data access logic, making code more testable and flexible. Bind a concrete repository to an interface via the Service Container.)What is the Service Layer pattern? Should business logic go in controllers or models?
(Expert opinion: Controllers handle HTTP, Models handle data, a Service Layer handles complex business rules. This keeps classes slim and focused.)When would you use Laravel Queues? Describe a scenario and how you'd implement it.
Scenario: Sending welcome emails to 10,000 new users.
Implementation: Dispatch a
SendWelcomeEmail
job to a queue.
How do Laravel Queues work under the hood? Explain the relationship between jobs, workers, and the queue database/Redis.
(Jobs are pushed to a queue driver (e.g., Redis). Workers run continuously, listening to the queue and processing jobs.)What are Laravel Events and Listeners? How do they facilitate a decoupled application design?
(An event is fired when something significant happens. Listeners react to that event without the firing code needing to know about them.)
Deep Dive into the Container
Explain the difference between
bind()
,singleton()
, andinstance()
methods in the Service Container.bind()
: A new instance is resolved every time.singleton()
: The same instance is shared and returned every time.instance()
: Bind an existing object instance.
How does Service Provider deferred loading work?
(A provider can be deferred if it only registers bindings and doesn't need to execute on every request, improving performance.)
Advanced Security
How can you prevent SQL injection in Laravel? Is Eloquent enough?
(Yes, Eloquent and the Query Builder use PDO parameter binding, making them inherently secure against SQL injection. The risk comes from using raw queries unsafely.)Explain XSS and how Laravel helps protect against it. When are you still vulnerable?
Protection: The
{{ }}
Blade syntax automatically escapes output.Vulnerability: When using
{!! !!}
on user-provided data without sanitization.
What is Mass Assignment and how does Laravel protect against it? Can you give an example of a vulnerable mass assignment implementation?
Protection: The
$fillable
or$guarded
properties on the model.Vulnerable Example:
// In Controller Post::create($request->all()); // If the model has no $fillable/$guarded, a user could pass `is_admin => true`.
Performance & Scaling
How would you optimize a Laravel application for high traffic? List strategies from database to application to server level.
Database: Indexing, query optimization, read/write replicas.
Application: Caching (Redis/Memcached), Queues, OPCache, Composer Optimize.
Server: CDN, Load Balancers, Horizontal Scaling.
What is Laravel Octane? How does it fundamentally change the request lifecycle, and what are the trade-offs?
(Uses Swoole/RoadRunner to keep the application bootstrapped in memory between requests, dramatically increasing performance. Trade-off: requires careful management of static/global state.)
Advanced Eloquent & Database
How would you update a table with millions of records without locking it or causing downtime?
(Use chunking and avoidget()
:User::chunk(1000, function ($users) { ... });
or use cursors.)What are Polymorphic Relationships? Describe a real-world scenario and implement it.
Scenario:
Comment
s can belong to aPost
or aVideo
.Implementation:
// comments table: id, body, commentable_id, commentable_type class Comment extends Model { public function commentable() { return $this->morphTo(); } } class Post extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
API & Microservices
How would you design a rate-limiting strategy for a public API in Laravel?
(Use Laravel's built-inthrottle:60,1
middleware for simple cases. For more complex needs (per-user, per-endpoint), implement a custom solution using the Cache.)How can you implement API versioning in Laravel?
(Common strategies: URL prefix (/api/v1/posts
), HTTP headers (Accept: application/json; version=1.0
).)What are the challenges of moving from a monolith to a microservices architecture with Laravel? How would you share authentication between services?
(Challenges: Data consistency, network latency, debugging. Authentication: Use a shared OAuth2 server (Passport) or JWT tokens.)
Expert Level Questions (Continued) <a name="expert"></a>
Testing & TDD
What is the difference between Unit Tests, Feature Tests, and Integration Tests in the context of Laravel?
Unit: Tests a single class or method in isolation (often with mocks).
Feature: Tests a larger portion of code, like a full API endpoint or user interaction, interacting with the framework.
Integration: Tests the interaction between multiple components (e.g., a service and a repository).
How would you test a queued job without actually pushing it to a queue?
Use Laravel'sQueue::fake()
and then assert the job was pushed.public function test_job_is_pushed() { Queue::fake(); // Execute the code that dispatches the job ProcessPodcast::dispatch($podcast); // Assert a job was pushed... Queue::assertPushed(ProcessPodcast::class); }
How do you mock an external API call within a Laravel test?
Use Laravel'sHttp
facade to fake responses.Http::fake([ 'weather-api.com/*' => Http::response(['temp' => 72], 200), ]); // Your code that calls the API will now get this fake response.
Deployment & DevOps
What is the purpose of the
php artisan optimize
command in a deployment process? Is it still necessary in recent Laravel versions?
*(It caches the bootstrap files. As of Laravel 5.8+, it's largely unnecessary for performance in production if you're using OPcache, butconfig:cache
androute:cache
are still critical.)*How does Laravel Forge or Envoyer simplify deployment? What underlying principles do they use?
(They automate zero-downtime deployments, often using symbolic links for thecurrent
release and managing queues and Horizon during deployment.)Explain a zero-downtime deployment strategy for a Laravel application.
Build the new version of the app in a new directory (
releases/v2
).Run
composer install
,npm build
,php artisan config:cache
.Symlink shared storage (
storage
,.env
) to the new release.Atomically switch the
current
public symlink to point to the new release.Run database migrations after the symlink switch (to avoid downtime if they fail).
Reload PHP-FPM.
Advanced Problems & Scenarios
Scenario: Your Laravel application is suddenly very slow. Describe your step-by-step debugging process.
Step 1: Check Laravel Debugbar or Telescope for slow queries, N+1 problems.
Step 2: Check server metrics (CPU, RAM, I/O) –
htop
,iotop
.Step 3: Check slow query logs in the database.
Step 4: Check application logs (
storage/logs/laravel.log
) for errors.Step 5: Check cache and queue driver connectivity (Redis, Beanstalkd).
How would you implement a real-time notification feature (like a live news ticker) in Laravel? Compare different approaches.
Polling: Simple (
setInterval
in JS to hit an API) but inefficient.Laravel Echo Server + WebSockets: Modern, efficient, real-time. Uses Pusher or a Laravel WebSocket server.
Server-Sent Events (SSE): Simpler than WebSockets, one-way communication from server to client.
You need to process a large CSV file (1GB+) and import its rows into the database. How would you architect this in Laravel to avoid memory limits?
Use Laravel's
job
batches.Read the file in chunks using generators (
fgetcsv
in a loop).Dispatch a job for each chunk of rows (e.g., 1000 rows per job).
Use a queue worker (e.g., Horizon) to process the jobs.
How do you handle database transactions in Laravel? Write an example where you create a new user and their first post in a single transaction.
DB::transaction(function () use ($request) { $user = User::create($request->only('name', 'email')); // If this fails, the user creation is rolled back $user->posts()->create($request->only('title', 'content')); });
What are Value Objects? How would you implement one in Laravel, perhaps for a Money value (amount and currency)?
(A value object is an immutable object whose equality is based on its property values, not its identity. Implementation often involves Casts.)// In the Model protected $casts = [ 'price' => MoneyCast::class, ]; // MoneyCast class would serialize/deserialize to a Money object.
Explain the CQRS (Command Query Responsibility Segregation) pattern. How could its principles be applied in a Laravel project?
Principle: Separate the model that reads data (Queries) from the model that writes data (Commands).
Laravel Application: Use simple Eloquent models for reads. Use dedicated Action or Service classes (e.g.,
CreateOrderAction
) for writes, which encapsulate all the business logic.
How would you implement a multi-tenant SaaS application in Laravel (where each customer has isolated data)?
Approach 1: Separate databases per tenant. Use a central DB to track tenants and their database connections. Dynamically switch connections.
Approach 2: Single database, with a
tenant_id
on all tenant-specific tables. Use a global scope to automatically scope all queries by the currenttenant_id
.Package: Often implemented using packages like stancl/tenancy.
Final Set of Questions (Mix of Complexities) <a name="final"></a>
What is the
scheduling
feature in Laravel? How does it work on a server?
(TheApp\Console\Kernel::schedule
method defines commands to run. On the server, a single cron entry* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
runs every minute and Laravel evaluates if any tasks are due.)What are Macros? How would you add a custom method to the Eloquent Builder?
php use Illuminate\Database\Eloquent\Builder; Builder::macro('active', function () { return $this->where('is_active', 1); }); // Usage: User::active()->get();
What is the purpose of the
App\Exceptions\Handler
class?
(The central place to handle how your application responds to exceptions: reporting them and rendering HTTP responses.)How can you customize the pagination views generated by Laravel?
php artisan vendor:publish --tag=laravel-pagination
What are the benefits of using API Resources?
(Transform and format Eloquent models and collections into JSON API responses, acting as a transformation layer.)What is the difference between
softDeletes()
andforceDelete()
?
*softDeletes()
: Setsdeleted_at
timestamp. Model is not included in future queries.
*forceDelete()
: Permanently removes the record from the database.How do you create a custom validation rule?
php artisan make:rule Uppercase
Implement thepasses
andmessage
methods.What is the
has()
method used for in Eloquent?
(To query based on the existence of a relationship.User::has('posts')->get()
gets all users who have at least one post.)How would you implement a "remember me" functionality during authentication?
(The Laravelauth
middleware handles this out-of-the-box. It involves a long-lived cookie and a token stored in theusers
table.)What is the purpose of the
$casts
property in an Eloquent model?
(To define attributes that should be converted to common data types, likearray
,json
,datetime
, orboolean
.)How do you handle localization (i18n) in Laravel?
(Use the__()
helper function. Translation strings are stored in files in theresources/lang
directory.)What is the
replicate()
method used for in Eloquent?
(To create a new, unsaved instance of a model with all its attributes copied. Useful for creating "duplicate" records.)How can you monitor your Laravel application in production?
(Tools: Laravel Telescope, Laravel Horizon, monitoring services (Sentry, Bugsnag), APM tools (DataDog, New Relic).)What is the
tap()
helper function used for?
(It allows you to "tap" into a fluent chain, perform an action on the passed value, and then return the value. Useful for debugging or adding side effects within a chain.)How would you implement a search feature across multiple model attributes?
(Use a package like Laravel Scout with a driver like Algolia or Meilisearch for advanced full-text search. For simpler needs, usewhere()
clauses withorWhere()
.)What is method injection in a controller? How is it different from constructor injection?
(You can type-hint dependencies in a controller's method in addition to the constructor. The container will inject them. Useful for dependencies only needed in a single method.)php public function store(Request $request, ImageProcessor $processor) { ... }
Explain the concept of "contracts" in Laravel. What is the
Illuminate\Contracts
namespace?
(Contracts are interfaces that define the core services provided by the framework (e.g.,Cache
,Queue
,Mailer
). Using interfaces makes code more flexible and testable.)How does Laravel's authentication system work behind the scenes?
(It uses guards (e.g.,web
,api
) and providers (e.g.,eloquent
). The session guard maintains state using cookies, while the token guard authenticates via an API token.)What is the purpose of the
php artisan down
andup
commands?
(To put your application into maintenance mode and bring it back online.)How can you extend a Blade component?
(Use component slots and thex-slots
syntax to create flexible layouts.)What is the
resolve()
helper function used for?
(To resolve a class instance out of the service container.)$api = resolve('MyApiService');
How would you handle a situation where you need to change the structure of a cached config file during deployment?
(Always runphp artisan config:cache
at the end of your deployment process to recache the new configuration.)What is the
optional()
helper function used for?
(To avoid null pointer errors. It allows you to call methods or access properties on an object that might benull
. If the object isnull
, the call will returnnull
instead of causing an error.)return optional($user->address)->country;
Describe how you would implement a feature that requires long-running PHP processes (like a WebSocket server).
(Use a process manager like Supervisor to run and monitor Laravel Echo Server or a custom Artisan command as a daemon.)What is the difference between
where()
andwhereIn()
?
*where('column', 'value')
: Checks if a column equals a single value.
*whereIn('column', [1, 2, 3])
: Checks if a column's value is present in a given array of values.How can you share a variable with all your Blade templates?
(Use a View Composer, often registered in a service provider'sboot()
method.)php View::composer('*', function ($view) { $view->with('categories', Category::all()); });
What is the
Gate::before()
method used for?
(To define a callback that is run before all other authorization checks. If it returns a non-null result, that result will be considered the result of the check. Useful for granting full access to admins.)How would you create a console command that asks the user for input?
(Use theask()
,confirm()
, andchoice()
methods within the command'shandle()
method.)What is the
Collection
class? Why is it powerful?
(A wrapper around arrays providing a fluent, convenient interface for mapping, reducing, filtering, and transforming data.)How do you handle circular dependencies within the Service Container?
(This is often a sign of bad design. Refactor the code to remove the circular dependency. If absolutely necessary, use a setter injection instead of a constructor injection to break the cycle.)Explain the Lazy Collections feature. When would you use it?
(Lazy Collections leverage PHP generators to handle massive datasets with very low memory usage. You'd use it when processing huge files or large database results.)$users = User::cursor()->filter(...); // Returns a LazyCollection
How would you implement a custom Filesystem Disk (e.g., to store files on FTP or SFTP)?
(Define the disk's driver and configuration inconfig/filesystems.php
. Laravel's Flysystem integration makes this possible.)What is the purpose of the
$hidden
property on an Eloquent model?
(To specify which attributes should be hidden when the model is converted to an array or JSON (e.g.,password
,api_token
).)Describe a scenario where you would use a
Pivot
model in a Many-to-Many relationship.
(When the intermediate (pivot) table has additional attributes beyond the foreign keys. For example, arole_user
pivot table might have aassigned_by
andassigned_at
column.)How does Laravel's encryption work? What is required to decrypt data?
*(It uses OpenSSL for AES-256-CBC encryption. TheAPP_KEY
in the.env
file is essential. Data encrypted with oneAPP_KEY
cannot be decrypted with another.)*
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam