Laravel Interview Questions and Answers 2026

What changed in 2026 drives
Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.
What I'd actually study for this
- 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
- 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
- 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
- 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken
Where most candidates trip up
The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.
Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.
Laravel is the most widely used PHP framework for web application development. Candidates report that Eloquent ORM and relationships, the service container and dependency injection, middleware, queues and jobs, authentication (Sanctum/Passport), and Artisan commands are the most heavily tested topics in PHP and full-stack developer interviews. This guide covers 50 questions from fundamentals to advanced patterns. Always confirm the Laravel version in use at your target company on their official careers portal.
Table of Contents
- Laravel Fundamentals
- Routing and Middleware
- Eloquent ORM
- Service Container and Providers
- Authentication and Authorization
- Queues and Events
- Testing and Advanced Patterns
- 5-Question Mock Test
- Frequently Asked Questions
Laravel Fundamentals
Q1. What is the request lifecycle in Laravel? Medium
- Entry point:
public/index.phploads the autoloader and retrieves the application instance frombootstrap/app.php - HTTP Kernel (
app/Http/Kernel.php) bootstraps the framework (config, environment, facades, service providers) - Global middleware pipeline runs (CORS, session, auth)
- Router matches the URL to a route; route-specific middleware runs
- Controller method (or closure) executes; returns a Response
- Response travels back through the middleware pipeline (terminated middleware)
- Response sent to client
Q2. What is the artisan command-line tool? Easy
Artisan is Laravel's CLI. Key commands:
php artisan make:model Post -mrcf # model + migration + controller + factory
php artisan make:middleware Throttle
php artisan make:job SendEmail
php artisan make:event OrderPlaced
php artisan make:listener NotifyUser
php artisan migrate
php artisan migrate:rollback
php artisan migrate:fresh --seed # drop all + migrate + seed
php artisan queue:work --tries=3 # start queue worker
php artisan queue:failed # list failed jobs
php artisan queue:retry all # retry all failed
php artisan cache:clear
php artisan config:cache # production optimization
php artisan route:list # view all routes
php artisan tinker # REPL with full app context
Q3. What are Service Providers in Laravel? Medium
Service Providers are the central place to bootstrap application components (bind classes to the container, register event listeners, configure packages). Every provider has register() (bind to container) and boot() (called after all providers are registered).
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Services\PaymentService;
use App\Contracts\PaymentGateway;
use App\Services\StripeGateway;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Bind interface to implementation
$this->app->bind(PaymentGateway::class, StripeGateway::class);
// Singleton: same instance every resolve
$this->app->singleton(PaymentService::class, function ($app) {
return new PaymentService($app->make(PaymentGateway::class));
});
}
public function boot(): void
{
// Runs after all providers registered; safe to resolve
\Illuminate\Support\Facades\Blade::directive('money', function ($expression) {
return "<?php echo number_format($expression, 2); ?>";
});
}
}
Q4. What is the service container and dependency injection? Medium
// Type-hint in constructor - Laravel auto-resolves
class OrderController extends Controller
{
public function __construct(
private readonly OrderRepository $orders,
private readonly PaymentGateway $payment,
) {}
public function store(StoreOrderRequest $request)
{
$order = $this->orders->create($request->validated());
$this->payment->charge($order);
return response()->json($order, 201);
}
}
// Resolve manually
$service = app(PaymentGateway::class);
$service = resolve(PaymentGateway::class);
// Contextual binding: different impl for different classes
$this->app->when(CheckoutController::class)
->needs(PaymentGateway::class)
->give(StripeGateway::class);
$this->app->when(TestCheckoutController::class)
->needs(PaymentGateway::class)
->give(FakeGateway::class);
Q5. What is the difference between config(), env(), and .env? Easy
.env is environment-specific configuration not committed to source control. env() reads .env values at runtime. config() reads cached config files from config/ directory.
In production, php artisan config:cache merges all config files into a cache. After caching, env() calls in application code (outside config files) return null because the .env file is no longer read. Always access env values through config files.
// WRONG in production after config:cache
$key = env('STRIPE_KEY'); // null after cache
// CORRECT: access via config
// config/services.php
return ['stripe' => ['key' => env('STRIPE_KEY')]];
// In code:
$key = config('services.stripe.key'); // always works
Routing and Middleware
Q6. How does Laravel routing work? Easy
// routes/web.php
use App\Http\Controllers\PostController;
// Basic routes
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
// Resource controller (7 CRUD routes)
Route::resource('posts', PostController::class);
Route::apiResource('posts', PostController::class); // no create/edit (form pages)
// Route model binding
Route::get('/posts/{post}', function (Post $post) {
return $post; // Laravel resolves Post by ID automatically
});
// Custom binding key
Route::get('/posts/{post:slug}', [PostController::class, 'show']);
// Grouping with prefix and middleware
Route::prefix('admin')
->middleware(['auth', 'admin'])
->group(function () {
Route::resource('users', UserController::class);
Route::resource('posts', AdminPostController::class);
});
Q7. How do you create and use middleware? Medium
// php artisan make:middleware EnsureUserIsVerified
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureUserIsVerified
{
public function handle(Request $request, Closure $next): mixed
{
if (!$request->user()->hasVerifiedEmail()) {
return redirect('/email/verify');
}
$response = $next($request); // continue to next middleware/controller
// After middleware (response phase)
$response->headers->set('X-Response-Time', microtime(true));
return $response;
}
}
// Register in app/Http/Kernel.php or bootstrap/app.php (Laravel 11)
// Laravel 11 uses bootstrap/app.php:
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'verified' => EnsureUserIsVerified::class,
]);
})
// Usage on route
Route::get('/dashboard', DashboardController::class)->middleware('verified');
// Or class-based
Route::get('/dashboard', DashboardController::class)
->middleware(EnsureUserIsVerified::class);
Q8. What is route model binding? Easy
// Implicit binding: type-hint Eloquent model in controller
public function show(Post $post): View
{
// Laravel queries Post::findOrFail($id) automatically
return view('posts.show', compact('post'));
}
// Custom binding key (route: /posts/{post:slug})
// Model needs getRouteKeyName()
class Post extends Model
{
public function getRouteKeyName(): string
{
return 'slug';
}
}
// Explicit binding in RouteServiceProvider or provider
Route::model('post', Post::class);
// Or custom resolution:
Route::bind('post', function (string $value) {
return Post::where('slug', $value)->firstOrFail();
});
// Scoped binding: /users/{user}/posts/{post} (post must belong to user)
Route::scopeBindings()
->group(function () {
Route::get('/users/{user}/posts/{post}', [PostController::class, 'show']);
});
Eloquent ORM
Q9. What are Eloquent relationships and how do you define them? Medium
class User extends Model
{
// One to Many: user has many posts
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
// One to One: user has one profile
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
// Many to Many: user belongs to many roles (pivot table)
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class)
->withPivot('assigned_at')
->withTimestamps();
}
}
class Post extends Model
{
// Inverse: post belongs to user
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
// Polymorphic: post has many comments
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
// Has many through: post has many country (through user)
public function country(): HasOneThrough
{
return $this->hasOneThrough(Country::class, User::class);
}
}
Q10. What is eager loading and how do you solve the N+1 problem? Medium
The N+1 problem occurs when you load a collection and then access a relationship for each item, causing N additional queries.
// N+1 PROBLEM: 1 query for posts + N queries for each author
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query per post!
}
// EAGER LOADING: 2 queries total
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name; // no query, already loaded
}
// Multiple relationships
$posts = Post::with(['author', 'comments.user', 'tags'])->get();
// Constrained eager loading
$posts = Post::with([
'comments' => function ($query) {
$query->where('approved', true)->latest()->limit(3);
}
])->get();
// Lazy eager loading (after collection retrieved)
$posts = Post::all();
$posts->load('author');
// Prevent lazy loading (Laravel 10+)
// In AppServiceProvider::boot()
Model::preventLazyLoading(!app()->isProduction());
Q11. What are Eloquent scopes? Medium
class Post extends Model
{
// Local scope
public function scopePublished(Builder $query): Builder
{
return $query->where('status', 'published');
}
public function scopeByCategory(Builder $query, string $category): Builder
{
return $query->where('category', $category);
}
public function scopeRecent(Builder $query, int $days = 30): Builder
{
return $query->where('created_at', '>=', now()->subDays($days));
}
}
// Usage (Laravel strips 'scope' prefix)
Post::published()->get()
Post::published()->byCategory('tech')->recent(7)->paginate(15)
// Global scope: applies to ALL queries on the model
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model): void
{
$builder->where('is_active', true);
}
}
// In model:
protected static function booted(): void
{
static::addGlobalScope(new ActiveScope);
// Or inline:
static::addGlobalScope('active', fn($q) => $q->where('is_active', true));
}
// Remove global scope
Post::withoutGlobalScope(ActiveScope::class)->get()
Post::withoutGlobalScopes()->get() // remove all
Q12. What are Eloquent observers and model events? Medium
// Model events: creating, created, updating, updated, saving, saved,
// deleting, deleted, restoring, restored, retrieved
class Post extends Model
{
protected static function booted(): void
{
static::creating(function (Post $post) {
if (empty($post->slug)) {
$post->slug = Str::slug($post->title);
}
});
static::deleting(function (Post $post) {
$post->comments()->delete(); // cascade delete
});
}
}
// Observer class (for many events)
// php artisan make:observer PostObserver --model=Post
class PostObserver
{
public function creating(Post $post): void
{
$post->user_id = auth()->id();
}
public function created(Post $post): void
{
Cache::forget('posts.count');
event(new PostCreated($post));
}
public function deleted(Post $post): void
{
// clean up storage, etc.
}
}
// Register in AppServiceProvider
Post::observe(PostObserver::class);
Q13. What is the difference between find, first, firstOrFail, and findOrFail? Easy
Post::find(1) // find by primary key; returns null if not found
Post::find([1, 2, 3]) // collection of models
Post::first() // first record matching query; null if none
Post::where('slug', $slug)->first()
Post::firstOrFail() // first or throw ModelNotFoundException (404)
Post::where('slug', $slug)->firstOrFail()
Post::findOrFail(1) // find by PK or throw ModelNotFoundException
// firstOr: fallback value/callback
Post::where('slug', $slug)->firstOr(fn() => new Post(['slug' => $slug]))
// firstOrCreate: find or create
Post::firstOrCreate(
['slug' => $slug], // search conditions
['title' => 'Default title'] // additional fill on create
)
// updateOrCreate
Post::updateOrCreate(
['slug' => $slug],
['title' => $request->title, 'content' => $request->content]
)
Authentication and Authorization
Q14. What is Laravel Sanctum and how does it differ from Passport? Medium
| Feature | Sanctum | Passport |
|---|---|---|
| Use case | SPA + mobile token auth | Full OAuth2 server |
| Token type | Personal access tokens, cookie session | OAuth2 tokens |
| Complexity | Simple | Complex |
| Setup | Built-in | Requires additional setup |
| OAuth2 grants | No | Yes (code, implicit, password, client credentials) |
| Best for | Own SPA, mobile apps, internal APIs | Third-party auth, public APIs |
// Sanctum token auth
$token = $user->createToken('mobile-app', ['read:posts', 'write:posts']);
$plainToken = $token->plainTextToken;
// Validate token in request
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn(Request $r) => $r->user());
});
// Check abilities
$request->user()->tokenCan('write:posts')
Q15. What are Laravel Gates and Policies? Medium
Gates are closure-based authorization checks. Policies are class-based for model authorization.
// Gate (simple, non-model)
Gate::define('view-admin', function (User $user) {
return $user->role === 'admin';
});
Gate::define('update-post', function (User $user, Post $post) {
return $user->id === $post->user_id;
});
// In controller
$this->authorize('view-admin'); // throws 403 if fails
Gate::allows('update-post', $post) // bool
Gate::denies('update-post', $post)
// Policy (class-based, model-specific)
// php artisan make:policy PostPolicy --model=Post
class PostPolicy
{
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id || $user->isAdmin();
}
}
// In controller
$this->authorize('update', $post);
// In Blade
@can('update', $post)
<button>Edit</button>
@endcan
Queues and Events
Q16. How do Laravel queues work? Medium
// Create a job
// php artisan make:job SendWelcomeEmail
class SendWelcomeEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 30; // seconds between retries
public function __construct(private readonly User $user) {}
public function handle(Mailer $mailer): void
{
$mailer->to($this->user)->send(new WelcomeMail($this->user));
}
public function failed(\Throwable $exception): void
{
// Notify admin of failure
Log::error('WelcomeEmail failed', ['user' => $this->user->id]);
}
}
// Dispatch
SendWelcomeEmail::dispatch($user);
SendWelcomeEmail::dispatch($user)->delay(now()->addMinutes(10));
SendWelcomeEmail::dispatch($user)->onQueue('emails');
// Chaining
Bus::chain([
new ProcessPayment($order),
new SendReceipt($order),
new NotifyWarehouse($order),
])->dispatch();
// Worker
// php artisan queue:work redis --queue=emails,default --tries=3
Q17. What are Laravel Events and Listeners? Medium
Events provide a simple observer pattern implementation.
// php artisan make:event OrderShipped
class OrderShipped
{
use Dispatchable, SerializesModels;
public function __construct(public readonly Order $order) {}
}
// php artisan make:listener SendShipmentNotification --event=OrderShipped
class SendShipmentNotification implements ShouldQueue
{
public function handle(OrderShipped $event): void
{
Mail::to($event->order->user)->send(new ShipmentNotification($event->order));
}
}
// Register in EventServiceProvider (Laravel < 11) or Providers/AppServiceProvider
Event::listen(OrderShipped::class, SendShipmentNotification::class);
// Dispatch
OrderShipped::dispatch($order);
event(new OrderShipped($order));
// Multiple listeners, different queues
Event::listen(OrderShipped::class, [
SendShipmentNotification::class,
UpdateInventory::class,
LogShipment::class,
]);
Testing and Advanced Patterns
Q18. How do you test a Laravel application? Medium
// Feature test (HTTP level)
class PostTest extends TestCase
{
use RefreshDatabase; // reset DB between tests
public function test_authenticated_user_can_create_post(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->postJson('/api/posts', [
'title' => 'Test Post',
'content' => 'Content here',
]);
$response->assertStatus(201)
->assertJsonStructure(['id', 'title', 'slug', 'author']);
$this->assertDatabaseHas('posts', ['title' => 'Test Post']);
}
public function test_guest_cannot_create_post(): void
{
$response = $this->postJson('/api/posts', ['title' => 'Test']);
$response->assertUnauthorized();
}
}
// Unit test (model/service level)
class PostTest extends TestCase
{
public function test_slug_generated_on_create(): void
{
$post = Post::factory()->create(['title' => 'Hello World']);
$this->assertEquals('hello-world', $post->slug);
}
}
// Mocking
$this->mock(PaymentGateway::class, function (MockInterface $mock) {
$mock->shouldReceive('charge')->once()->with($order)->andReturn(true);
});
// Queue/Event assertions
Queue::fake();
Event::fake();
SendWelcomeEmail::dispatch($user);
Queue::assertPushed(SendWelcomeEmail::class);
OrderShipped::dispatch($order);
Event::assertDispatched(OrderShipped::class, fn($e) => $e->order->id === $order->id);
Q19. What is the Repository pattern in Laravel? Advanced
The Repository pattern abstracts data access, making it easier to swap implementations and test.
// Interface
interface PostRepository
{
public function find(int $id): ?Post;
public function findBySlug(string $slug): ?Post;
public function create(array $data): Post;
public function paginate(int $perPage = 15): LengthAwarePaginator;
}
// Eloquent implementation
class EloquentPostRepository implements PostRepository
{
public function find(int $id): ?Post
{
return Post::with('author')->find($id);
}
public function findBySlug(string $slug): ?Post
{
return Post::with('author')->where('slug', $slug)->first();
}
public function create(array $data): Post
{
return Post::create($data);
}
public function paginate(int $perPage = 15): LengthAwarePaginator
{
return Post::with('author')->published()->latest()->paginate($perPage);
}
}
// Bind in service provider
$this->app->bind(PostRepository::class, EloquentPostRepository::class);
// Controller uses interface
class PostController extends Controller
{
public function __construct(private readonly PostRepository $posts) {}
public function index(): JsonResponse
{
return response()->json($this->posts->paginate());
}
}
Q20. What are Laravel Collections and their most useful methods? Medium
$users = User::all(); // returns Collection
// Filtering
$admins = $users->filter(fn($u) => $u->role === 'admin');
$active = $users->where('is_active', true);
$named = $users->whereIn('name', ['Alice', 'Bob']);
// Transformation
$names = $users->map(fn($u) => $u->name);
$emails = $users->pluck('email', 'id'); // keyed by id
$grouped = $users->groupBy('role');
$sorted = $users->sortBy('name');
$sorted = $users->sortByDesc('created_at');
// Aggregation
$count = $users->count();
$sum = $users->sum('salary');
$avg = $users->avg('age');
// Utilities
$users->each(fn($u) => $u->sendNotification());
$chunks = $users->chunk(100);
$unique = $users->unique('email');
$first = $users->first(fn($u) => $u->role === 'admin');
// Lazy collections (memory-efficient for large datasets)
LazyCollection::make(function () {
$cursor = Post::cursor(); // DB cursor, not all in memory
foreach ($cursor as $post) {
yield $post;
}
})->filter(fn($p) => $p->isPublished())->each(fn($p) => $p->reindex());
5-Question Mock Test
Q1. Explain the N+1 problem in Eloquent. How do you detect and fix it?
Q2. What is the difference between bind(), singleton(), and instance() in the Laravel service container?
Q3. How does route model binding work? What happens when the model is not found?
Q4. Write a Laravel queue job that sends a welcome email with 3 retries and a 60-second delay between retries.
Q5. What is the difference between Gate::define() and a Policy class? When would you use each?
Answers:
A1. N+1: loading N posts then querying author for each = 1 + N queries. Detect with Laravel Debugbar or Model::preventLazyLoading(). Fix with Post::with('author')->get() (eager loading).
A2. bind(): new instance every resolve. singleton(): same instance every resolve after first creation. instance(): bind an already-created object as the singleton.
A3. Laravel calls Model::findOrFail($routeParam). If not found, throws ModelNotFoundException which the exception handler converts to a 404 HTTP response.
A4. Job class implementing ShouldQueue with public int $tries = 3; and public int $backoff = 60;. The handle() method sends the mail.
A5. Gate::define() is for simple, non-model-specific checks (can-access-admin). Policies are for model-specific authorization (can-update-THIS-post). Use Gates for general permissions; use Policies for per-resource CRUD authorization.
Frequently Asked Questions
What is Laravel Sanctum used for?
Sanctum provides authentication for SPAs (Single Page Applications), mobile apps, and simple token-based APIs. It issues simple API tokens stored in the database and can use Laravel's session-based authentication for same-domain SPAs. Use Sanctum when you own the client; use Passport when you need to issue tokens to third-party applications via OAuth2.
What are the differences between Laravel 10 and Laravel 11?
Laravel 11 introduced a slimmer application structure (single bootstrap/app.php for middleware/routes/exceptions, no separate Http/Kernel.php), per-second rate limiting, the once() helper for memoized closures, health routing, and PHP 8.2 as the minimum version. Candidates report that interviewers sometimes ask about these structural changes.
How does Eloquent differ from the Query Builder?
Eloquent is Active Record: each model hydrates a PHP object with relationships, events, and casts. The Query Builder returns plain arrays/stdObjects (faster for bulk operations). Use Eloquent for standard CRUD with relationships and events; use Query Builder for batch inserts, complex aggregates, or performance-critical bulk reads.
What is the internal mesh of related topics?
- PHP Interview Questions 2026 - PHP fundamentals and OOP patterns behind Laravel
- Flask Interview Questions 2026 - compare Python micro-framework approach
- Spring Framework Interview Questions 2026 - compare Java DI/IoC container patterns
- MySQL Interview Questions 2026 - database queries and indexing that Eloquent generates
Methodology applied to this articlelast verified 8 Jun 2026
- No fabricated salary numbers or success rates. If we quote a range, it's sourced.
- No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
- No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Explore this topic cluster
More resources in Interview Questions
Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.
Paid contributor programme
Sat this this year? Share your story, earn ₹500.
First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.
Submit your story →Ready to practice?
Take a free timed mock test
Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.
Start Free Mock Test →Related Articles
Airbnb Interview Questions 2026: Top Tech, HR & Behavioural Q&As for Freshers
Clearing Airbnb's fresher loop in 2026 comes down to preparing for the exact mix of questions across technical, behavioural,...
Airtel Interview Questions 2026: Top Tech, HR & Behavioural Q&As for Freshers
Clearing Airtel's fresher loop in 2026 comes down to preparing for the exact mix of questions across technical, behavioural,...
AMD Interview Questions 2026: Top Tech, HR & Behavioural Q&As for Freshers
Clearing AMD's fresher loop in 2026 comes down to preparing for the exact mix of questions across technical, behavioural,...
Atlassian Interview Questions 2026: Top Tech, HR & Behavioural Q&As for Freshers
Clearing Atlassian's fresher loop in 2026 comes down to preparing for the exact mix of questions across technical,...
Barclays Interview Questions 2026
_Last verified by [Aditya Sharma](/author/aditya-sharma/) · cross-checked against PapersAdda Hiring Pulse and...
More from PapersAdda
Accenture Interview Questions 2026 (with Answers for Freshers)
Capgemini Interview Questions 2026 (with Answers for Freshers)
HCLTech Interview Questions 2026 (TechBee + TGT, with Answers)
IBM Interview Questions 2026 (with Answers for Freshers)