Laravel interview questions and answers for PHP developers

Laravel interview questions test whether you understand what happens between an HTTP request and a JSON response: routing and route model binding, form requests that validate and authorize, Eloquent relationships, scopes and casts, events, queues and transactions, and how you prove it all works with feature tests. Experienced candidates are also asked where the framework's magic costs them, from hidden queries to state that leaks between requests under Octane.

By Published 8 min read

How Laravel interviews usually run

Laravel roles range from agencies shipping many small apps to product companies with one large codebase and a team of PHP developers. Most loops mix three things: questions about how the framework works, a practical task such as adding an endpoint with validation, authorization and a test, and a review of existing code where the interviewer has planted a slow query, a missing policy check or a job that runs twice. A take-home is common at smaller companies; larger teams more often pair with you live for an hour.

The language layer, including types, comparisons and the basics of the service container and N+1, is covered in PHP interview questions. This page assumes that and stays on the framework.

Fundamentals: requests, routes and validation

Laravel fundamentals for junior and mid-level developers
QuestionWhat it testsWhat a strong answer shows
Walk me through the request lifecycle.Framework modelpublic/index.php loads the autoloader and the application, the HTTP kernel runs bootstrappers and registers providers, the request passes through global middleware, the router matches a route and runs its middleware, the controller returns a response, and it travels back out through the middleware.
What is route model binding?RoutingA type-hinted model parameter whose name matches the route segment is fetched for you, with a 404 if it does not exist. You can bind by another column, such as a slug, or scope a child to its parent.
What does a form request give you over validating in the controller?Validation designRules and authorization live in one class, run before the controller, and return 422 with errors for JSON requests or redirect back with errors for forms. The controller only sees validated data.
What do sometimes, nullable and required differ on?Validation rulesrequired needs a non-empty value. nullable allows null while still checking other rules. sometimes runs the rules only when the field is present, which suits partial updates.
How do you make a unique rule ignore the current record?Validation detailsUse the Rule::unique builder with ignore on the model being updated, so renaming a record to its own name still passes.
Resource controllers: what do you get?ConventionsSeven conventional actions mapped to routes, or five with apiResource. It keeps naming predictable and works with policies through authorizeResource or per-action checks.
Why run route:cache and config:cache on deploy?PerformanceThey compile routes and config into single cached files so each request skips that work. Closures in route files and env() calls outside config files are the usual reasons it breaks.
Where is middleware registered in recent versions?Version awarenessFrom Laravel 11 the default skeleton configures middleware in bootstrap/app.php rather than an HTTP Kernel class. Older apps still have the Kernel; both are worth recognizing.
Laravel fundamentals for junior and mid-level developers. Scroll sideways on a small screen.
// routes/api.php
Route::patch('/projects/{project}', [ProjectController::class, 'update'])
    ->middleware('auth:sanctum');

// app/Http/Requests/UpdateProjectRequest.php
class UpdateProjectRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('update', $this->route('project'));
    }

    public function rules(): array
    {
        return [
            'name' => ['sometimes', 'string', 'max:120',
                Rule::unique('projects')->ignore($this->route('project'))],
            'due_on' => ['nullable', 'date', 'after:today'],
            'owner_id' => ['sometimes', 'exists:users,id'],
        ];
    }
}

// app/Http/Controllers/ProjectController.php
public function update(UpdateProjectRequest $request, Project $project): ProjectResource
{
    $project->update($request->validated());

    return new ProjectResource($project->fresh('owner'));
}
A partial update: route model binding, a form request that authorizes through a policy, and an API resource for the response.

Eloquent questions beyond eager loading

  • belongsToMany with extra pivot columns: how do you read and write them? Declare withPivot for the columns and withTimestamps if needed, then attach, sync or updateExistingPivot. For real behavior on the link, give the pivot its own model with using.
  • When would you use a polymorphic relationship? When one model can belong to several types, such as comments on posts and on videos. Store a morph map so the database holds short aliases instead of class names that break when you rename a class.
  • What is hasManyThrough? Access to distant records through an intermediate model, such as a country's posts through its users, in one query.
  • whereHas versus with a constraint? whereHas filters the parent rows by a condition on the relation. A constrained with filters which related rows get loaded. You often need both, which withWhereHas combines in newer versions.
  • Local versus global scopes? A local scope is a reusable query method you call by name. A global scope applies to every query on the model, as soft deletes do, and can surprise people, so document it and know withoutGlobalScope.
  • What do casts do? Convert attributes on the way in and out: dates to Carbon instances, JSON columns to arrays, and backed enums to enum cases. Encrypted casts store the value encrypted at rest.
  • Accessors and mutators in modern Laravel? A method returning an Attribute with get and set closures. Keep them cheap, since they run every time the attribute is read or the model is serialized.
  • Observers or model events: any risks? They hide side effects. Bulk queries such as a mass update do not fire them, and doing slow work inside them slows every save. Prefer explicit domain events for important actions.
  • How do soft deletes interact with unique indexes? A soft-deleted row still holds its unique value, so recreating the same email fails. Options include a partial or composite index, or restoring the old row.
class Invoice extends Model
{
    protected function casts(): array
    {
        return [
            'paid_at' => 'datetime',
            'status' => InvoiceStatus::class, // a backed enum
            'meta' => 'array',
        ];
    }

    public function scopeOverdue(Builder $query): void
    {
        $query->whereNull('paid_at')->where('due_on', '<', now());
    }

    protected function totalFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => number_format($this->total_cents / 100, 2),
        );
    }
}

// Customers with failed payments, loading only the failed ones
$customers = Customer::whereHas('payments', fn ($q) => $q->where('status', 'failed'))
    ->with(['payments' => fn ($q) => $q->where('status', 'failed')])
    ->get();

$late = Invoice::overdue()->with('customer')->get();
A model with casts, a local scope and an accessor, then a filtered and eager-loaded query.

Intermediate: events, transactions, scheduling and caching

Questions that come up once you have shipped Laravel apps
QuestionWhat it testsWhat a strong answer shows
A queued listener sees a record that does not exist yet. Why?TransactionsThe event was dispatched inside a database transaction, and a worker picked up the job before the commit. Use after-commit dispatch on the job or listener, or the queue connection's after_commit setting.
Events and listeners versus calling services directly?DesignEvents decouple side effects such as emails, analytics and cache busting from the action. The trade-off is indirection, so keep the core flow explicit and use events for genuine fan-out.
How does the scheduler work?SchedulingOne cron entry runs schedule:run every minute, and Laravel decides which tasks are due. withoutOverlapping and onOneServer stop duplicate runs across slow tasks and multiple servers.
How do you prevent two workers handling the same thing?ConcurrencyAtomic locks with Cache::lock on a shared store, unique jobs, or a database row lock with lockForUpdate inside a transaction, depending on what is being protected.
Notifications versus Mailables?MessagingA Mailable is one email. A notification describes a message once and sends it over several channels, such as mail, database and Slack, chosen per recipient.
What does an API resource add over returning a model?API designControl over the JSON shape, conditional fields, nested resources only when loaded, and consistent pagination meta, without leaking columns you add later.
How do you rate limit an API?ProtectionDefine named limiters keyed by user or IP and attach them with the throttle middleware. Return 429 with retry headers, and set tighter limits on login and expensive endpoints.
Cache tags and invalidation: what goes wrong?CachingTags work only on stores that support them, keys built from user input can explode, and forgetting to bust a key after writes serves stale data. Cache::remember with a clear key scheme and a short TTL is a safe start.
Questions that come up once you have shipped Laravel apps. Scroll sideways on a small screen.

Senior and scenario questions

  • Sanctum or Passport? Sanctum covers first-party single-page apps with cookie sessions and simple personal API tokens. Passport is a full OAuth2 server for third-party clients. Pick by who your clients are, not by habit.
  • What changes under Octane? The application stays in memory between requests, so singletons, static properties and anything resolved once can carry one user's data into another request. Audit bindings, reset state, and watch memory over time.
  • How do you structure a large Laravel app? Group by domain or feature rather than by framework folder once it grows, keep controllers thin with actions or services, and draw boundaries so modules talk through clear interfaces and events.
  • How do you deploy with zero downtime? Build releases in a fresh directory, run composer install with an optimized autoloader, cache config and routes, run backward-compatible migrations, switch a symlink, then restart queue workers so they load the new code.
  • Scenario: a nightly report job sometimes sends twice. Check retries after a timeout, the worker timeout versus retry_after, and whether the scheduler runs on several servers. Make the job idempotent and use onOneServer or a unique job.
  • Scenario: the API returns a 500 only in production. Look at logs and the exception handler output, compare cached config with the environment, check file permissions on storage and cache, and confirm the queue and cache drivers match what the code assumes.
  • Scenario: a customer table needs multi-tenancy. Compare a tenant column with a global scope against a database per tenant. Talk about leaks through missing scopes, queued jobs that must carry the tenant, and how tests prove isolation.
  • How do you keep a big test suite fast? Database transactions or in-memory databases where safe, factories that create only what a test needs, parallel testing, and faking mail, queues, events and HTTP so tests never call real services.
use App\Models\Project;
use App\Models\User;
use Laravel\Sanctum\Sanctum;

it('lets the owner rename a project', function () {
    $owner = User::factory()->create();
    $project = Project::factory()->for($owner, 'owner')->create();
    Sanctum::actingAs($owner);

    $this->patchJson("/api/projects/{$project->id}", ['name' => 'Renamed'])
        ->assertOk()
        ->assertJsonPath('data.name', 'Renamed');

    expect($project->fresh()->name)->toBe('Renamed');
});

it('forbids other users', function () {
    $project = Project::factory()->create();
    Sanctum::actingAs(User::factory()->create());

    $this->patchJson("/api/projects/{$project->id}", ['name' => 'Nope'])
        ->assertForbidden();
});
Feature tests in Pest for the endpoint above: the owner can rename, another user gets a 403.

Fictional example

Answering "Describe a bug that only showed up in production"
Interviewer
Tell me about a Laravel bug you could not reproduce locally.
Candidate
Customers sometimes got an order confirmation email with an empty item list. Locally it never happened, because the queue ran in sync mode. In production, the OrderPlaced event fired inside the checkout transaction, and the queued mail listener sometimes ran before the items were committed. I marked the listener to run after commit and added a regression test around the checkout flow. I also changed the queue connection to dispatch after commit by default, then checked the other listeners for the same pattern. The empty emails stopped, and we added the sync-versus-real queue difference to our onboarding notes.

Practice plan for a Laravel interview

  1. Build one small API end to endProjects and tasks with Sanctum auth, a policy, form requests, API resources and pagination. Write feature tests for every endpoint, including the forbidden cases.
  2. Model awkward relationshipsAdd tags through a pivot with extra columns, polymorphic comments and a hasManyThrough report, and check the SQL each query runs.
  3. Make async work failQueue an email inside a transaction, watch it misbehave with a real worker, then fix it. Add a scheduled job and prove it cannot overlap.
  4. Review someone else's codeTake an open-source Laravel app, find one missing authorization check, one slow query and one side effect hidden in an observer. Practice explaining each in two minutes.
  5. Run a timed mockSixty minutes: add an endpoint with validation, a policy and tests while talking through your choices out loud.

If the role sits on Node.js instead, the same ideas appear with decorators and modules in NestJS interview questions. For the wider backend loop, see backend developer interview questions.

For mock rounds, Natively works as an AI interview assistant on Mac or Windows. It keeps a transcript of the session, so you can check whether your answer on after-commit dispatch was as clear as it felt. It can read a Laravel task from a screenshot during practice and suggest an approach or a test you forgot, and with Pro or the free trial it draws on the résumé and job description you provide. Transcripts and notes stay available for later study.

Questions people ask

What Laravel questions are asked in interviews?

The request lifecycle, routing and route model binding, form requests and validation, Eloquent relationships, scopes and casts, events and queues, transactions, caching and locks, authentication with Sanctum and feature testing.

What Laravel questions do experienced developers get?

Scenarios: a queued job that runs twice, a listener that sees uncommitted data, state leaking under Octane, multi-tenancy, zero-downtime deploys and how to structure a large codebase by domain.

How are Laravel and PHP interview questions different?

PHP questions cover the language: types, comparisons, OOP and security basics. Laravel questions cover the framework on top: how a request is handled, Eloquent, validation, queues, events and testing.

Is there a practical task in a Laravel interview?

Usually. A common one is an API endpoint with validation, a policy check, an API resource and feature tests, done as a take-home or in a live pairing session of about an hour.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP