Request lifecycle, service container, Eloquent and N+1, queues, validation, auth and the questions that separate Laravel users from Laravel developers.
Readiness: 0 of 28 nailed
How to use this page:1. Read a question2. Type your answer3. Check with AI4. Open the model answer5. Timed drill when you’re 70% ready
A request enters through one front door (public/index.php), passes security checks (middleware), finds the right room (route), meets the person who handles it (controller), and walks back out through the same checks with a response.
Say it like this in the interview
“public/index.php loads the autoloader and bootstraps the application. The HTTP kernel runs global middleware, service providers register and boot bindings, the router matches the route and runs route middleware like auth, then the controller action runs, usually using models and services, and returns a response. That response travels back through middleware before being sent.”
They will probably ask next
“What is a service provider?” The place where you register bindings and boot things like events and routes.
The container is a smart vending machine for objects. You ask for a PaymentGateway in your controller’s constructor and Laravel builds and hands you the right one, including everything *it* needs, automatically.
// AppServiceProvider::register()
$this->app->bind(PaymentGateway::class, StripeGateway::class);
// Controller: Laravel resolves it automatically
public function __construct(private PaymentGateway $payments) {}
Say it like this in the interview
“The container resolves class dependencies automatically using reflection and lets me bind interfaces to implementations in a service provider. Controllers, jobs and listeners get dependencies injected by type-hint. It makes code testable, because in tests I can swap the binding for a fake.”
They will probably ask next
“bind vs singleton?” bind creates a new instance each time; singleton reuses one.
When one action should trigger several independent side effects (order placed → email, invoice, analytics), the controller just announces “order placed!” and each listener reacts. The controller doesn’t need to know about all of them.
Say it like this in the interview
“Events decouple side effects from the main action. OrderPlaced is dispatched once, and separate listeners send emails, update stock, notify Slack. Listeners can be queued. I’m careful not to overuse them: hidden flows can make code hard to follow, so for one simple side effect a direct call is clearer.”
Facades are short static-looking shortcuts like Cache::get(). Behind the scenes, Laravel fetches the real object from the service container and calls the method on it.
Say it like this in the interview
“A facade extends Facade and returns a container binding key from getFacadeAccessor. __callStatic resolves the instance and forwards the call. They’re convenient and testable via Cache::shouldReceive() or fakes, but injecting dependencies makes them more explicit in services.”
Laravel looks at the class’s constructor using reflection, sees what types it needs, builds those (and their dependencies) recursively, then builds your class.
Say it like this in the interview
“Auto-wiring via reflection: for each constructor parameter it resolves the type-hinted class recursively. Interfaces and primitives need explicit bindings, contextual binding when different consumers need different implementations, and make or app() to resolve manually.”
You fetched 100 posts in one trip, then went back to the database once per post to get its author: 1 + 100 trips. That’s the N+1 problem. Eager loading fetches all the authors in one extra trip.
Say it like this in the interview
“It’s the N+1 problem: each $post->author triggers a lazy-loaded query. I fix it with eager loading: Post::with('author')->latest()->take(100)->get(), which makes it two queries. I also enable Model::preventLazyLoading() in development so it throws an exception whenever lazy loading happens.”
User::create($request->all()) saves whatever the form sent. If an attacker adds is_admin=1 to the form, they become admin. $fillable is the whitelist of fields allowed to be filled that way.
Say it like this in the interview
“Mass assignment is filling a model from an array. $fillable whitelists assignable attributes; $guarded blacklists. I prefer $fillable and pass $request->validated() rather than $request->all(), so only validated fields reach the model.”
Ways to connect tables: a user has many posts; a post belongs to a user; posts and tags belong to many of each other through a pivot table; comments can belong to posts or videos (polymorphic).
Say it like this in the interview
“hasMany/belongsTo use a foreign key on the child table; belongsToMany uses a pivot table with withPivot and withTimestamps for extra columns; polymorphic relations use commentable_id and commentable_type so one model can belong to several types. hasManyThrough reaches across an intermediate model.”
Scopes are reusable named filters on your model, so you don’t repeat the same where clauses everywhere.
class Post extends Model {
public function scopePublished(Builder $query): void {
$query->whereNotNull('published_at')->where('published_at', '<=', now());
}
}
$posts = Post::published()->with('author')->paginate(20);
Say it like this in the interview
“Local scopes are methods prefixed with scope (or marked with the #[Scope] attribute in newer versions) that I chain like Post::published()->latest(). Global scopes apply automatically to every query, as with soft deletes.”
Casts automatically convert database values into useful types (JSON text into an array, 0/1 into true/false, strings into dates or enums). Accessors and mutators let you transform values when reading or writing.
Say it like this in the interview
“casts converts attributes to arrays, booleans, dates, enums, encrypted values or custom cast classes. Accessors and mutators via Attribute::make(get:, set:) format values, like a computed full_name or lowercasing emails on save.”
Don’t load all 2 million into memory. Process in batches, or let the database do the update in one SQL statement.
Say it like this in the interview
“If the change is the same for all rows, a single query: Model::where(...)->update([...]). Otherwise chunkById(1000, fn ($rows) => ...), which is safe while modifying, or lazyById() for a generator. Run it in a queued job or Artisan command, not a web request.”
A Form Request is a bouncer class: it checks every field before the controller even runs, and automatically sends errors back if something is wrong.
// php artisan make:request RegisterRequest
class RegisterRequest extends FormRequest {
public function authorize(): bool { return true; }
public function rules(): array {
return [
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'email', 'unique:users,email'],
'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
];
}
}
public function store(RegisterRequest $request) {
$user = User::create([...$request->validated(), 'password' => Hash::make($request->password)]);
}
Say it like this in the interview
“I use a Form Request class for validation and authorization, keeping the controller thin. On failure Laravel redirects back with errors, or returns 422 JSON for API requests. I only use validated() data afterwards.”
Middleware is a checkpoint every request passes through before reaching the controller. It can let the request continue or stop it.
class EnsureAdmin {
public function handle(Request $request, Closure $next): Response {
abort_unless($request->user()?->is_admin, 403);
return $next($request);
}
}
Route::middleware(['auth', EnsureAdmin::class])->group(function () {
Route::get('/admin', AdminController::class);
});
Say it like this in the interview
“A middleware class with handle($request, $next) checks the user and aborts with 403 otherwise, then is applied to routes. For fine-grained rules I prefer Gates and Policies, with middleware like can:manage-users.”
Don’t make the user wait while you post the letter. Write it, drop it in an outbox (queue), say “done!”, and let a background worker deliver it.
class SendWelcomeEmail implements ShouldQueue {
use Queueable;
public $tries = 3;
public function __construct(public User $user) {}
public function handle(): void { Mail::to($this->user)->send(new Welcome($this->user)); }
}
SendWelcomeEmail::dispatch($user);
// run workers: php artisan queue:work (supervised by Supervisor / Horizon)
Say it like this in the interview
“Move it to a queued job or a queued Mailable, with Redis or the database as the queue driver, and run workers under Supervisor or Horizon. I configure retries and backoff, and handle failures in failed_jobs. Jobs should be idempotent because they can run more than once.”
Traps that make people fail
Forgetting that queued jobs serialise models and re-fetch them, so a deleted model makes the job fail.
Is anything actually processing the queue, and if so, why does the job fail?
Say it like this in the interview
“Check workers are running under Supervisor or Horizon and were restarted after deploy; the QUEUE_CONNECTION is not sync or wrong; the failed_jobs table and logs; timeouts versus retry_after; serialised models deleted before processing; memory limits. Horizon gives a dashboard for Redis queues.”
Sanctum is the lightweight option: cookie sessions for your own SPA and simple API tokens for mobile apps. Passport is a full OAuth2 server, needed only if *other* companies’ apps log in with your users’ accounts.
Say it like this in the interview
“Sanctum for first-party SPAs using cookie-based session auth with CSRF protection, and personal access tokens for mobile. Passport only when I need a full OAuth2 server for third-party clients. Authorization itself goes in Policies and Gates, not in controllers.”
They answer “is this user allowed to do this?”. Gates are simple yes/no rules; Policies group rules for one model (can this user update this post?).
Say it like this in the interview
“Gates are closures for general abilities; Policies are classes with methods like update(User $user, Post $post) mapped to a model. I call $this->authorize('update', $post) in controllers, @can in Blade, or can: middleware. Authorization stays out of controllers and is testable.”
Sanctum’s cookie login for SPAs needs the front end and API to share a domain setup, and the CSRF cookie must be fetched first.
Say it like this in the interview
“The SPA must call /sanctum/csrf-cookie first, send requests with credentials (withCredentials), and the SPA domain must be in SANCTUM_STATEFUL_DOMAINS. SESSION_DOMAIN must cover both subdomains, and CORS must allow credentials from that origin.”
Migrations are version control for your database structure: each file is one step (“add a phone column”). Every environment replays the same steps in order. Editing an old step doesn’t re-run it anywhere it already ran, so environments drift apart.
Say it like this in the interview
“Migrations describe schema changes in code, tracked in the migrations table. Once a migration has run in shared environments, I never edit it; I create a new one. For big production tables I think about locking: adding indexes or columns can lock the table, so I plan zero-downtime changes.”
“DB::transaction(function () { ... }) commits on success and rolls back on exception, with an optional retry count for deadlocks. I avoid sending emails or calling external APIs inside the transaction; I dispatch jobs afterCommit instead.”
In production you run php artisan config:cache, which bakes all config into one file and stops reading .env. Any env() call outside the config files then returns null.
Say it like this in the interview
“Because config is cached. env() should only be called inside config/*.php files; application code reads values with config('services.api.key'). My deploy runs config:cache, route:cache, view:cache, migrations with --force, and restarts queue workers with queue:restart so they load new code.”
Traps that make people fail
Forgetting to restart queue workers. They keep running old code.
Find out where time goes: database queries, external calls, or PHP work. Measure, then fix the biggest part.
Say it like this in the interview
“Look at Laravel Telescope or Pulse in staging, or an APM like New Relic, to see queries and timings. Common issues: N+1 queries, missing indexes, loading large collections, synchronous external calls, uncached config or routes. Fix with eager loading, indexes, pagination, caching and queues.”
Store the result with a name and expiry. When the data changes, delete that stored copy.
$top = Cache::remember('products:top', now()->addMinutes(10), fn () =>
Product::withCount('orders')->orderByDesc('orders_count')->take(10)->get());
// in Product model
protected static function booted(): void {
static::saved(fn () => Cache::forget('products:top'));
}
Say it like this in the interview
“Cache::remember('key', $ttl, fn () => ...) for read-through caching; on model events, Cache::forget the key, or use cache tags with Redis to flush groups. Cache::flexible gives stale-while-revalidate in newer versions.”
Octane keeps your app loaded in memory between requests (with Swoole, RoadRunner or FrankenPHP), so it skips booting the framework every time: much faster. But data left over from one request can leak into the next.
Say it like this in the interview
“Octane boots the app once and serves many requests from long-lived workers. The risk is state leakage: static properties, singletons holding request data, or injecting the request into singletons. I avoid storing request state in singletons, use scoped bindings, and watch memory growth.”
A layer that decides exactly how your model looks as JSON, so you don’t accidentally expose fields like passwords and the format stays consistent.
Say it like this in the interview
“JsonResource classes transform models into JSON with a toArray method; ResourceCollection handles lists with pagination meta. They decouple the API contract from the database schema and allow conditional fields with whenLoaded.”
Laravel makes it easy to call your routes in tests and check the response and the database, with fake versions of mail, queues and storage.
Say it like this in the interview
“Feature tests with Pest or PHPUnit using $this->postJson(), assertStatus, assertJson and assertDatabaseHas; RefreshDatabase for a clean database; factories for data; Mail::fake(), Queue::fake(), Http::fake() for external effects. Unit tests for pure services.”
Don’t throw everything into app/Models and huge controllers. Group code by business area and keep business rules in their own classes.
Say it like this in the interview
“Organise by domain modules (Billing, Catalog, Orders) each with its models, actions or services, events and policies; thin controllers calling action classes; Form Requests for validation; events for cross-module communication; and clear boundaries so a module could be extracted later. Microservices only when team or scaling needs justify the operational cost.”
Store a short code for each long URL, redirect quickly when someone visits the code, and count clicks without slowing redirects.
Say it like this in the interview
“A links table with a unique indexed code, generated as base62 of the ID or random with collision retry. The redirect route looks up the code, cached in Redis, and returns a 302 for analytics or 301 for permanence. Click tracking is dispatched to a queue to keep redirects fast. Rate limiting and URL validation prevent abuse.”