Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 67 ยท Practice and Review

Laravel Interview Questions

Prepare for a Laravel interview with clear answers on the request lifecycle, the service container, Eloquent, queues, security and performance, plus tips.

Laravel interviews tend to circle the same ideas: what happens when a request arrives, how the container wires objects together, how Eloquent turns tables into objects, how to keep slow work out of the request, and how to keep an app secure and fast. This lesson collects questions in those areas, each with an answer short enough to say out loud and a line about what interviewers usually listen for.

Do not memorize the wording. Interviewers can tell, and they follow up with "why?" or "what would you do if...?". Read each answer, close the page, and explain it in your own words, ideally with a tiny example from a project you built. If you have not built one yet, the project lessons are a good source of material.

The Laravel code in this lesson is read-only, since Laravel cannot run on this site. Two short plain-PHP stand-ins (a container and a middleware pipeline) let you experiment with ideas that interviewers love to ask about. They are simplifications, not Laravel's own code.

flowchart TD
    A["public/index.php"] --> B["bootstrap/app.php<br/>creates the application"]
    B --> C["Service providers<br/>register, then boot"]
    C --> D["Global middleware"]
    D --> E["Router matches a route"]
    E --> F["Route middleware"]
    F --> G["Controller or closure"]
    G --> H["Response travels back out<br/>through the middleware"]
    H --> I["Sent to the client, then terminate()"]

The request lifecycle in one picture: a good answer to the most common opening question.

Lifecycle and architecture

1. What happens when a request reaches a Laravel app?

The web server sends every request to public/index.php. It loads Composer's autoloader and bootstrap/app.php, which creates the application and configures routing and middleware. Service providers register and boot the framework's services. The request then goes through the global middleware, the router finds the matching route, route middleware runs, and the controller returns a response. The response travels back out through the middleware (in reverse order), is sent to the browser, and terminable middleware and terminate() callbacks run last. See the request lifecycle.

Listen-for: middleware order, providers, and that boot happens before routing.

2. What is middleware, and in which order does it run?

Middleware is a layer around the request handler. Each one receives the request and a $next closure; it can act before calling $next, after it, or return a response itself (like a redirect to login). Think of an onion: the request goes in through the layers in order and the response comes back out in reverse. Global middleware runs on every request; group middleware (web, api) on routes in a group; route middleware only where you attach it. See middleware.

The stand-in below shows the onion. The first middleware in the list is the outermost layer:

PHP Middleware order: in and back out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that when auth blocks the request, the headers layer and the controller never run, but the outer logging layer still gets its "after" step. That is why a logging or timing middleware belongs at the outside.

3. What is the service container?

The container is a registry that knows how to build objects and builds them for you. Type-hint a class in a controller, job or listener constructor and Laravel creates it, recursively resolving that class's own dependencies. You can tell it how to build things with bind() (a new instance each time), singleton() (one shared instance) or by binding an interface to an implementation. It is dependency injection with the wiring done for you. See the service container.

Listen-for: "automatic resolution through reflection" and one concrete benefit, such as swapping a payment gateway for a fake in tests.

4. Show me what automatic resolution does.

The stand-in below uses reflection to read constructor types, and shows an interface binding, a singleton and a concrete class that needs no registration:

PHP A tiny autowiring container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Welcome was never registered, yet it was built, because its constructor types told the container what it needs. bind gives a fresh LogMailer every time, while the singleton clock is shared.

5. What is the difference between register() and boot() in a service provider?

register() only binds things into the container; it must not use other services, because they may not be registered yet. boot() runs after every provider has registered, so it can safely use any service: register event listeners, define gates and rate limiters, share view data. See service providers.

6. How do facades work, and are they a bad idea?

A facade is a static-looking class (Cache::get()) whose __callStatic method resolves the real object from the container and forwards the call. They are not true static calls: in tests you can replace them (Cache::shouldReceive(...), Mail::fake()). The honest trade-off is that they make it easy to hide how many dependencies a class has. Many teams use facades in controllers and routes, and constructor injection in domain classes.

7. What are contracts?

Contracts are the interfaces under Illuminate\Contracts that describe framework services (Illuminate\Contracts\Cache\Repository, Queue, Mail\Mailer). Type-hinting a contract documents that your class needs "something that can cache", and lets you swap the implementation.

Eloquent and databases

8. What is the N+1 problem and how do you fix it?

Loading N models and then touching a relationship on each one runs one query for the list plus N more. Fix it with eager loading: Post::with('author')->get() runs two queries in total. Use withCount() for counts, constrain with with(['comments' => fn ($q) => $q->latest()->limit(3)]), and turn on Model::preventLazyLoading() in development so mistakes throw. See eager loading.

9. What is mass assignment and how does Laravel protect against it?

Mass assignment is filling many attributes at once, as in Post::create($request->all()). If a client can send is_admin=1 and your model accepts it, they promote themselves. Laravel makes you list the allowed columns in $fillable (or the forbidden ones in $guarded); everything else is ignored or throws, depending on configuration. Prefer $fillable plus validated data from $request->validated().

10. What is the difference between find(), findOrFail() and first()?

find($id) returns the model or null. findOrFail($id) throws ModelNotFoundException, which Laravel renders as a 404, so you rarely need to check for null by hand. first() returns the first row of a query, or null; firstOrFail() is its throwing twin.

11. firstOrCreate, updateOrCreate and upsert: when do you use each?

firstOrCreate fetches a row by attributes or creates it if missing, leaving existing rows untouched. updateOrCreate also updates an existing row. Both do a select then an insert or update, so under heavy concurrency a unique index is still needed to be safe. upsert() sends one INSERT ... ON CONFLICT/ON DUPLICATE KEY UPDATE for many rows at once and is the right tool for bulk imports; it needs a unique index on the key columns.

12. How do you process a very large table without running out of memory?

Do not get() it. Use chunkById(1000, fn ($rows) => ...) which pages by primary key (safe when you update rows while iterating), lazyById() or cursor() which stream one row at a time, or push the work into batched jobs. chunk() without "ById" can skip rows if the loop modifies the column it filters on.

13. What are accessors, mutators and casts?

They transform attributes on the way out of and into a model. An accessor formats a value on read, a mutator normalizes it on write, and casts convert automatically ('is_active' => 'boolean', 'options' => 'array', enums, encrypted values, dates to Carbon). In current Laravel, accessors and mutators are defined with the Attribute class in a method named after the attribute. See accessors, mutators and casts.

14. How do soft deletes work, and what is their catch?

With the SoftDeletes trait, delete() sets a deleted_at timestamp instead of removing the row, and Eloquent queries hide such rows by default (withTrashed() and onlyTrashed() show them). The catches: unique indexes still see the soft-deleted row (so a re-registered email can conflict), tables grow forever unless you prune, and raw queries ignore the scope. See model events and soft deletes.

15. Why use transactions, and how do you use them in Laravel?

A transaction makes several writes succeed or fail together, such as creating an order and its lines. DB::transaction(function () { ... }) commits when the closure returns and rolls back if it throws. Remember that jobs dispatched inside a transaction can run before it commits; use afterCommit() on the job or listener for those.

Queues, events and the scheduler

16. Why use queues, and what must you remember about jobs?

Queues move slow or unreliable work (mail, image processing, API calls) out of the request so users do not wait and failures can be retried. Remember that jobs can run more than once, so make them idempotent; keep payloads small (IDs, not big arrays); configure tries, backoff and timeout; handle failed(); and run queue:restart after a deploy because workers keep old code in memory. See queues and jobs.

17. What is the difference between dispatch() and dispatchSync()?

dispatch() sends the job to the configured queue connection for a worker to run later. dispatchSync() runs it immediately in the current process, which is useful in tests, console commands or when you really need the result now. The sync queue driver makes every dispatch behave that way.

18. Events versus jobs: what is the difference?

An event announces that something happened ("OrderShipped") and any number of listeners react, so the code that fires it does not know who cares. A job is one unit of work you want done, often in the background. Listeners can be queued, so the two combine well: fire an event, and let a queued listener do the slow part. See events and listeners.

19. How does the scheduler work?

You define tasks in code (Schedule::command('reports:daily')->dailyAt('02:00')), and the server runs php artisan schedule:run every minute through a single cron entry (or runs schedule:work). Laravel decides which tasks are due. Use withoutOverlapping() for tasks that may run long and onOneServer() when several servers share the schedule. See task scheduling.

Security

20. How does Laravel protect against CSRF, XSS and SQL injection?

  • CSRF: the web middleware group verifies a token on every state-changing request, and forms include it with @csrf.
  • XSS: Blade's {{ $value }} escapes HTML. {!! $value !!} does not, so use it only for content you fully trust or have sanitized.
  • SQL injection: the query builder and Eloquent use parameter binding. The danger is raw SQL with user input concatenated into the string; use whereRaw('x = ?', [$value]) with bindings.

See security in Laravel.

21. What is APP_KEY for?

It is the secret used to encrypt data (the encrypt() helper, encrypted cookies, session payloads where applicable) and to sign values such as signed URLs. Generate it once with php artisan key:generate, keep it secret and stable: changing it invalidates encrypted data and sessions, so rotate it deliberately.

22. Authentication versus authorization, and how are they done in Laravel?

Authentication answers "who are you?": guards and providers, starter kits, Fortify or Sanctum. Authorization answers "what may you do?": gates and policies, called with authorize(), Gate::allows() or @can. Always authorize on the server for every action, including actions triggered from Livewire or API clients; hiding a button is not protection. See gates and policies.

23. How are passwords stored?

Never in plain text or with fast hashes like MD5 or SHA-1. Laravel's Hash facade uses a slow, salted algorithm (bcrypt by default, Argon2 optional), the user model's hashed cast hashes automatically on assignment, and Hash::check() compares in a safe way. The work factor can be raised over time, and Hash::needsRehash() tells you when to upgrade stored hashes.

Performance and operations

24. How would you speed up a slow Laravel page?

Measure first (Debugbar or Telescope locally, a profiler or APM in production). Then, in order of payoff: fix N+1 queries and select only needed columns, add the right database indexes, paginate, cache expensive results with a sensible invalidation, move slow work to queues, and finally optimize the framework itself with php artisan optimize (config, route, event and view caches), OPcache and, for high traffic, Octane. See performance and optimization.

25. Why should you not call env() outside config files?

Once you run php artisan config:cache, Laravel stops loading the .env file and env() returns null in application code. Read environment values in config/*.php and use config('services.x.key') everywhere else. This is also why config and route caches belong to the deployment step, not to development.

26. What is the difference between config:cache and cache:clear?

config:cache compiles all configuration into one file for faster boot; config:clear removes it. cache:clear empties the application cache store (the data you put there with Cache::put). They are unrelated, and mixing them up is a classic cause of "my change has no effect".

27. How do you deploy a Laravel app without downtime?

Build the new release in a separate directory (install Composer dependencies with --no-dev, build assets), run migrations in a backward-compatible way, switch a symlink to the new release, then run php artisan optimize, restart queue workers and reload PHP-FPM. Platforms such as Laravel Cloud and Forge automate this. See deploying Laravel.

Testing

28. What would you test in a feature, and how do you keep tests fast?

Test behavior at the HTTP boundary: status codes, redirects, JSON structure, database changes and authorization, plus the one or two important failure cases. Use RefreshDatabase with SQLite in memory, factories for data, and fakes (Queue::fake(), Mail::fake(), Http::fake()) so tests never touch real services. Unit-test pure logic with plain classes. See testing with Pest and faking and mocking.

Tips for the interview

  • Answer in layers. Start with one sentence, then a detail, then an example. Stop when asked.
  • Name trade-offs. "Facades are convenient but hide dependencies" sounds senior; "facades are bad" or "facades are great" does not.
  • Bring a story. For each area, have one real example: a bug you fixed (an N+1), a risk you caught (a missing policy), a speedup you measured.
  • Say what you would check. When you do not know, explain how you would find out: the docs, route:list, php artisan about, the query log.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does middleware see a request and the response?

    Middleware forms an onion. Code before $next runs on the way in, in list order, and code after $next runs on the way out, in reverse order.
  2. 2. Why is register() in a service provider not the place to use other services?

    register() is for bindings only. Use boot() for anything that depends on other services.
  3. 3. A job dispatched inside a database transaction sometimes fails because the row it needs does not exist yet. What is the cleanest fix?

    The worker can pick up the job before the transaction commits. afterCommit() delays dispatching until the data is visible.
  4. 4. Which statement about env() is correct?

    Cached configuration means the .env file is no longer loaded at runtime. Config files read env(), and your code reads config().
  5. 5. What is the key difference between bind() and singleton() in the container?

    A singleton is created once per container and reused, while a plain binding creates a fresh object for each resolution.

Summary

  • Know the lifecycle: index.php, bootstrap, providers, middleware in, route, controller, middleware out.
  • Explain the container as automatic dependency injection, with bind, singleton and interface bindings.
  • For Eloquent, be ready on N+1, mass assignment, chunking, soft deletes and transactions.
  • For queues, say "idempotent, small payloads, retries, restart after deploy".
  • For security, cover CSRF, escaping, bindings, hashing and server-side authorization.
  • For performance, measure first, then queries, indexes, caching, queues and optimize.
  • Answer in layers, name trade-offs and bring one real story per topic.

Next: Laravel Cheat Sheet