PHP and Laravel interview questions and answers

PHP interview questions cover the language's type rules and quirks, object-oriented PHP with interfaces and traits, Composer and PSR standards, sessions, and web security: SQL injection, XSS, CSRF and password hashing. Most PHP jobs today also use a framework, so Laravel interview questions on the service container, Eloquent and the N+1 problem, middleware, queues and migrations usually come in the same loop. Answer with the safe default first, then the trap it avoids.

By Published 7 min read

How PHP and Laravel interviews are structured

PHP runs a large share of the web, from WordPress and e-commerce platforms to Laravel and Symfony applications, so interviews range from agency roles to product teams with large codebases. A common loop has a language and security screen, a practical task (often building or fixing a small CRUD feature or an API endpoint in Laravel), and a review conversation about performance, testing and deployment. Many teams care more about whether you write safe, maintainable code than about rare language trivia.

  1. PHP screenTypes, comparisons, arrays, OOP, traits, error handling. Short answers and one-line examples.
  2. Security questionsHow you prevent SQL injection, XSS and CSRF, store passwords, and handle sessions after login.
  3. Framework taskA Laravel endpoint with validation, an Eloquent relationship, a job on a queue and a test. Sometimes a take-home, sometimes live.
  4. Review and scaleFind the N+1 query in a controller, discuss caching, queues, migrations on a busy table and how you deploy.

PHP language questions

Core PHP questions for freshers and experienced developers
QuestionWhat it testsWhat a strong answer shows
What does declare(strict_types=1) change?Type checkingCalls made from that file to functions with scalar type declarations must pass exactly the right type, apart from int to float widening. Without it, PHP coerces values such as "10" to 10.
== versus ===?Comparison== compares after type juggling, === also requires the same type. PHP 8 made number-to-string comparisons saner, so 0 == "foo" is now false, but === is still the safe default.
How are objects passed to functions?Value semanticsBy handle: the function gets a copy of the handle, so it can change the object's properties but not replace the caller's variable. Arrays are copied on write.
What are references for, and why be careful?References& makes two names point to one value. They are useful in rare in-place array changes and easy to misuse, as the foreach example below shows.
isset, empty and is_null: how do they differ?Null handlingisset is false for undefined or null. empty is also true for falsy values like 0, "0" and an empty array. is_null warns on an undefined variable.
What does the null coalescing operator do?Syntax$a ?? $b returns $a if it is set and not null, otherwise $b, with no notice for undefined keys. The nullsafe ?-> stops a method chain at null.
What are generators?MemoryFunctions that use yield to produce values one at a time, so you can stream a large file or query result without building a huge array.
Error versus Exception?Error handlingBoth implement Throwable. Errors cover engine problems such as calling an undefined function or a TypeError; exceptions are thrown by code. Catch the narrowest type you can handle.
What does OPcache do?PerformanceIt stores compiled bytecode in shared memory, so scripts are not parsed and compiled on every request.
Core PHP questions for freshers and experienced developers. Scroll sideways on a small screen.
<?php
declare(strict_types=1);

function addTax(float $amount): float
{
    return $amount * 1.2;
}

echo addTax(10);    // 12: int to float is still allowed
echo addTax("10");  // TypeError here; coerced to 10.0 without strict_types
strict_types turns a silent conversion into a TypeError.
$items = [1, 2, 3];
foreach ($items as &$item) {
    $item *= 10;
}
// $item is still a reference to $items[2]
foreach ($items as $item) {
}
print_r($items);   // [10, 20, 20]

// Fix: unset($item); right after the first loop.
The foreach reference trap. The last element ends up overwritten.

Object-oriented PHP, Composer and PSR

  • Interface, abstract class or trait? An interface is a contract. An abstract class shares state and partial implementation with one parent. A trait copies methods into classes horizontally; it is not a type you can check with instanceof.
  • How do you resolve two traits with the same method? With insteadof to pick one and as to alias the other, inside the class's use block.
  • self versus static? self refers to the class where the code is written. static uses late static binding and refers to the class that was actually called, which matters in factory methods on parent classes.
  • Which magic methods come up most? __construct, __get and __set for inaccessible properties, __call for undefined methods, __toString and __invoke. Overusing them hides behavior from IDEs and static analysis.
  • What did PHP 8 add that you use daily? Constructor property promotion, named arguments, match expressions, union types and the nullsafe operator; PHP 8.1 added enums and readonly properties.
  • composer.json versus composer.lock? json declares allowed version ranges; lock records the exact versions installed. Applications commit the lock file so every environment installs the same code.
  • What is PSR-4? The autoloading standard that maps a namespace prefix to a directory, so Composer can load classes without require statements.
  • Which other PSRs matter? PSR-3 logging, PSR-7 HTTP messages, PSR-11 containers, PSR-15 middleware and the PSR-12 coding style, now continued as the PER coding style.

Sessions and security questions

// Values are sent separately from the SQL, so they cannot change the query.
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, $user['password_hash'])) {
    session_regenerate_id(true);   // new session ID after login
    $_SESSION['user_id'] = $user['id'];
}

// On sign-up:
$hash = password_hash($password, PASSWORD_DEFAULT);
Prepared statements with PDO, and password hashing with the built-in API.
Security questions asked in almost every PHP loop
QuestionWhat it testsWhat a strong answer shows
How do you prevent SQL injection?InjectionPrepared statements with bound parameters for every value. Identifiers such as column names cannot be bound, so check them against an allowlist.
How do you prevent XSS?Output encodingEscape on output for the right context: htmlspecialchars with ENT_QUOTES and UTF-8 in HTML, or a template engine that escapes by default. Add a Content Security Policy as a second layer.
What is CSRF and how is it stopped?Request forgeryAnother site makes the user's browser send an authenticated request. Use a per-session token in forms checked on every state-changing request, plus SameSite cookies.
How should passwords be stored?Hashingpassword_hash with PASSWORD_DEFAULT, password_verify to check, and password_needs_rehash to upgrade old hashes at login. Never MD5 or SHA-1, never your own salt scheme.
What is session fixation?SessionsAn attacker plants a known session ID before login. Regenerating the ID at login, and using HttpOnly, Secure and SameSite cookie flags, closes it.
Why is unserialize on user input dangerous?Object injectionIt can instantiate classes and trigger magic methods with attacker data. Use JSON for untrusted input.
How do you handle file uploads safely?UploadsCheck size and real type, generate your own file name, store outside the web root or on object storage, and never execute uploaded files.
Security questions asked in almost every PHP loop. Scroll sideways on a small screen.

Laravel interview questions

Laravel questions test whether you know what the framework does for you and where its convenience can hurt. The N+1 query is the single most common practical topic.

// N+1: one query for the posts, then one per post for its author
$posts = Post::latest()->take(50)->get();
foreach ($posts as $post) {
    echo $post->author->name;
}

// Eager loading: posts, then all their authors in one query
$posts = Post::with('author')->latest()->take(50)->get();

// In development, make accidental lazy loading throw:
Model::preventLazyLoading(! app()->isProduction());
Lazy loading in a loop runs one query per post. Eager loading runs two in total.
Laravel questions from junior to senior
QuestionWhat it testsWhat a strong answer shows
What is the service container?Dependency injectionA registry that builds objects and their dependencies, resolving type-hinted constructor parameters automatically. You bind interfaces to implementations in service providers.
bind versus singleton?Lifetimesbind builds a new instance each time it is resolved; singleton builds once and reuses it. Be careful with singletons holding per-request state in long-running workers such as Octane.
register versus boot in a service provider?Bootstrappingregister only binds things into the container. boot runs after all providers are registered, so it can use other services, register event listeners or routes.
What are facades?Static proxiesClasses like Cache or Log whose static calls are forwarded to an object in the container. They are convenient and still mockable in tests.
How does middleware work?Request pipelineEach middleware receives the request and a closure for the next layer, can act before or after it, or stop the request, as auth and CSRF middleware do.
What does mass assignment protection prevent?Eloquent securityFilling attributes like is_admin from request input. Declare fillable or guarded attributes, and pass validated data only.
When do you queue work?QueuesFor anything slow or unreliable in a request: emails, webhooks, report generation. Jobs should be idempotent, set tries and backoff, and be dispatched after the database transaction commits.
How do you change a large table without downtime?MigrationsAdd nullable columns first, backfill in batches with a job, switch code to the new column, then drop the old one in a later deploy. Avoid locking alters at peak.
Why does env() return null after config:cache?ConfigurationWith cached config, the .env file is not loaded, so env() should only be called inside config files and the app reads config() everywhere else.
Gates versus policies?AuthorizationGates are closures for simple checks; policies group authorization rules per model, such as update and delete on a Post.
Laravel questions from junior to senior. Scroll sideways on a small screen.
  • How would you process a million rows with Eloquent? chunkById or lazyById so memory stays flat, and a queued job per batch if the work is slow.
  • How do you test a controller that sends mail and dispatches a job? A feature test with RefreshDatabase, Mail::fake and Queue::fake, then assert on the response, the database and what was sent or pushed.
  • Why does Blade escape output with double curly braces? It runs htmlspecialchars, which prevents XSS. The unescaped form exists for trusted HTML only.
  • How would you speed up a slow Laravel page? Check the query log or a debug bar for N+1 and missing indexes first, then cache expensive reads with clear invalidation, and move slow work to queues.

Fictional example

Answering "Tell me about a performance problem you fixed in Laravel"
The admin orders page took several seconds to load once a client passed a few thousand orders. The debug bar showed over two hundred queries: the Blade view read each order's customer and item count lazily. I added with('customer') and withCount('items'), and put an index on the status and created-at columns the filter used. The page dropped to a handful of queries. To stop it coming back, I turned on preventLazyLoading outside production, which immediately flagged two other screens with the same pattern, and we fixed those in the same sprint.

Two-week PHP and Laravel preparation plan

  • Days 1 to 3: types, strict_types, comparisons, arrays and references. Write each snippet on this page and trace it before running.
  • Days 4 to 5: OOP, traits, late static binding, Composer and PSR-4. Build a tiny package with autoloading.
  • Days 6 to 8: security. Write a login with PDO, password_hash, session regeneration and a CSRF token, then try to break it.
  • Days 9 to 12: Laravel. A CRUD feature with Form Request validation, a policy, an eager-loaded relationship, a queued job and feature tests.
  • Days 13 and 14: a timed mock task, then a self-review for N+1 queries, missing indexes and unescaped output.

If the role mentions Rails too, Ruby on Rails interview questions cover the same MVC, N+1 and background job ideas from the Ruby side. For a compiled backend language often used next to PHP services, see Go interview questions, and for the full role loop, backend developer interview questions.

Natively, an AI interview assistant for Mac and Windows, records a transcript of each mock PHP or Laravel interview, so you can check whether your security answers named the exact defense. During practice it can read a coding task from a screenshot, suggest a hint or an approach, and with Pro or the free trial tailor answers to the résumé and job description you add. Transcripts and notes are kept for later study.

Questions people ask

What PHP questions are asked in interviews?

Types and strict_types, == versus ===, references, arrays, OOP with interfaces and traits, late static binding, Composer and PSR-4, error handling, and security: prepared statements, output escaping, CSRF tokens and password_hash.

What Laravel interview questions should I prepare?

The service container and service providers, facades, middleware, Eloquent relationships and the N+1 problem with eager loading, mass assignment, queues and jobs, migrations, config caching, and testing with fakes.

How do I answer PHP security questions?

Name the safe default and the attack it stops: bound parameters against SQL injection, context-aware escaping against XSS, tokens and SameSite cookies against CSRF, password_hash for storage and a new session ID after login.

Do PHP developer interviews include a coding task?

Usually. Common tasks are a CRUD feature or API endpoint in Laravel with validation and tests, or fixing a slow page with N+1 queries. Some teams send it as a take-home.

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