60 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended Laravel resources →
In Laravel, you want GET /users/{user} to call UserController@show. Which route definition is most natural?
Answer: Route::get('/users/{user}', [UserController::class, 'show']);
Route::get defines a route for GET requests. The array form can specify the controller class and method.
In Laravel, you want to receive a User model automatically from the {user} route parameter. Which feature is mainly used?
Answer: Route model binding
Route model binding can inject the matching Eloquent model into a controller argument from a route parameter.
In a Laravel controller, what is preferable to reading request input directly from $_POST?
Answer: Receive a Request object, validate it, and use it
Laravel's Request object lets you handle input, authorization, and validation using framework conventions.
Input validation is complex and reused by multiple controllers. Where is it natural to move it in Laravel?
Answer: Form Request class
A Form Request can move authorization and validation rules into a dedicated class, helping keep controllers thin.
In Laravel, for a one-to-many relationship between users and posts, which relation is typically defined on the User model?
Answer: hasMany(Post::class)
Because a user has many posts, the User model defines hasMany. From the post side back to the user, belongsTo is used.
A list page displays posts and authors and suffers from N+1 queries. What should you consider first in Laravel?
Answer: Use eager loading with with('user')
Eager loading preloads related models and reduces additional queries inside loops.
In Laravel, which model property is commonly used to handle mass assignment safely?
Answer: $fillable
$fillable explicitly lists attributes allowed for mass assignment. It helps prevent unintended column updates.
In Laravel, what is used to share database schema changes across a team and manage them as history?
Answer: Migration
Migrations manage database schema changes such as creating tables or adding columns as code.
Why does migration order matter when dropping tables with foreign key constraints?
Answer: Dropping a referenced table first can violate constraints
With foreign key constraints, you must plan the order, such as dropping constraints or child tables first.
In Laravel, you want to validate that email is required and has email format. Which rule set is representative?
Answer: 'email' => ['required', 'email']
required checks presence, and email checks email format. Complex inputs are often managed in a Form Request.
When validation fails in Laravel, what is the usual behavior for a normal web request?
Answer: Redirect back and flash error information to the session
For web requests, validation failure commonly redirects back and makes errors and old input available for display.
In Laravel, you want to restrict a route to authenticated users. What is commonly used?
Answer: auth middleware
The auth middleware protects routes that require authentication, such as redirecting guests to a login page.
In Laravel, where is CSRF protection mainly needed?
Answer: State-changing form submissions and POST/PUT/DELETE requests
CSRF abuses a user's authenticated state to cause unintended state changes. Token verification matters for state-changing requests.
You want to defer heavy work such as sending mail or processing images so the HTTP response is not delayed. What Laravel feature is commonly used?
Answer: Queue Job
Queue Jobs let you dispatch heavy work to a queue and process it asynchronously with workers.
Why is it often necessary to restart Laravel queue workers after deployment?
Answer: Workers are long-running and may not automatically reload new code
Queue workers are long-running processes, so deployment often requires restarting them to load new code or configuration.
Why is Blade's normal {{ $name }} output considered safer for displaying user input in HTML?
Answer: Because it outputs HTML-escaped content
Blade's {{ }} output is escaped by default. Raw output with {!! !!} should be used carefully.
You want to reuse a shared header or form part across multiple screens. What is a good Blade candidate?
Answer: Blade component
Blade components can reuse view parts and reduce template duplication.
In Laravel, where is it appropriate to organize logic that decides whether the logged-in user can update a specific post?
Answer: Policy
Policies organize authorization logic for models and reduce scattered checks in controllers or Blade views.
You want to get the authenticated user's information in a Laravel controller. Which method is representative?
Answer: $request->user()
$request->user() is a common way to get the currently authenticated user. Authorization can be combined with policies or gates.
In Laravel production, .env was changed but configuration did not update. What should you suspect first?
Answer: config cache
Production often uses config:cache. If configuration is cached, the cache must be regenerated after .env changes.
In Laravel, you want secrets to vary by environment without hard-coding them. What is the basic approach?
Answer: Use .env or external secret management and read through config
Secrets should be separated from source code and supplied through environment variables or secret management into configuration.
In Laravel, where is it basically defined that a certain URL should run a certain process?
Answer: routes/web.php
routes/web.php is commonly used for web route definitions. It maps URLs to controllers, closures, or other handlers.
Which description best matches the main role of a Laravel controller?
Answer: Receive a request, call the necessary processing, and return a response
A controller acts as an entry point for request handling. It calls models or services and returns responses such as views or JSON.
Which template engine is basically used in Laravel to build HTML views?
Answer: Blade
Blade is Laravel's standard template engine. It builds HTML with features such as layout inheritance, conditionals, and loops.
What does an Eloquent model in Laravel mainly represent?
Answer: A class for working with database tables and records in the application
An Eloquent model is a class for treating tables and records as objects. It is used for queries, saving data, and defining relationships.
In Laravel, what mechanism manages database structure changes such as creating tables or adding columns as code?
Answer: Migration
Migrations manage database schema changes as code. They help reproduce database structure across teams and environments.
You want to limit login attempts within a time window to reduce brute-force attacks against a Laravel login API. Which mechanism is appropriate?
Answer: RateLimiter or throttle middleware
Laravel rate limiting can control attempt counts using keys such as IP address or user identity. Combine it with uniform authentication responses, MFA, and monitoring.
For an unsubscribe link in email, you want to detect URL parameter tampering and enforce expiration. Which Laravel feature is appropriate?
Answer: A temporary signed URL with signed middleware
Laravel temporary signed URLs include a signature and expiration, while signed middleware validates tampering and expiry. A signed URL alone may not satisfy every identity-verification requirement.
In Laravel, you need to store a third-party service secret in the database and decrypt it when needed. Which approach is appropriate, distinct from password storage?
Answer: Use Laravel encryption or an encrypted cast and protect APP_KEY
Laravel encryption can protect secrets that must later be decrypted. APP_KEY protection and rotation planning are important. User passwords should be hashed and verified, not decrypted.
In a production Laravel environment, which setting should be checked at minimum to avoid exposing exception details, environment values, and stack traces?
Answer: APP_DEBUG=false
Set APP_DEBUG=false in production and inspect details through protected logs or monitoring. Do not expose .env or logs through the web, and validate configuration during deployment.
For a Laravel application served over HTTPS, you want session cookies unreadable by JavaScript and never sent over plaintext HTTP. Which settings should be checked?
Answer: Enable http_only and secure
HttpOnly restricts JavaScript access to the cookie, while Secure sends it only over HTTPS. SameSite should also be chosen according to CSRF and application requirements.
In Laravel, which type of test is appropriate for checking an HTTP endpoint's response status and displayed content?
Answer: Use a feature test to call get or post, then use assertStatus or assertSee
Laravel feature tests can send HTTP requests to the application and verify responses, authentication, and database state close to real usage.
In Laravel feature tests, which trait is commonly used to reset database state after tests?
Answer: RefreshDatabase
RefreshDatabase uses migrations or transactions during tests to keep database state clean and reduce cross-test data pollution.
After production deployment, .env values changed but Laravel still uses old configuration. Which operation should be checked first?
Answer: Clear or rebuild the configuration cache
When Laravel uses config:cache, configuration is read from cache. After changing .env, config:clear or rebuilding the cache is needed.
In Laravel, you want to reuse an expensive aggregate result for a fixed time and recompute after expiration. Which feature is appropriate?
Answer: Cache::remember
Cache::remember takes a key, expiration, and closure; it reuses cached data or computes and stores it when missing, reducing expensive aggregate load.
After order confirmation, you want to run multiple follow-up processes such as email and inventory integration in a loosely coupled way. Which Laravel design is appropriate?
Answer: Dispatch an event and split follow-up work into listeners
Laravel events and listeners separate the fact that an order was confirmed from follow-up processing. Listeners can also be queued when needed.
In Laravel, only the author should be allowed to update a post. Where is the appropriate place to organize authorization logic?
Answer: Policy
Policies organize operation permissions for models. Controllers and Blade can use them through authorize or @can.
In Laravel, you want to separate complex validation rules and authorization from the controller. Which mechanism is appropriate?
Answer: Form Request
Form Requests separate input validation and request-level authorization into dedicated classes, keeping controllers thin and easier to test.
In Laravel, you want to store uploaded files in an abstracted disk rather than directly under public/. Which feature is appropriate?
Answer: Storage facade and filesystem disks
Laravel's filesystem can configure disks such as local, public, or S3 and abstract storage through Storage, making visibility and URL generation easier to design.
In a Laravel production deployment, you want queue workers to pick up new code with minimal user impact. Which operation is appropriate?
Answer: Run php artisan queue:restart so workers restart gracefully
Laravel queue workers are long-running processes and may keep old code after deployment. queue:restart asks workers to restart safely after finishing current jobs.
An order insert and inventory decrement must both succeed, or both must be rolled back if an exception occurs. Which Laravel feature fits?
Answer: Perform both updates inside DB::transaction()
DB::transaction() commits when its closure completes and rolls back on an exception, providing a basic way to make related database updates atomic.
Concurrent requests overwrite updates to the same inventory row. What should be considered inside a transaction?
Answer: Retrieve the row with lockForUpdate()
lockForUpdate() requests an exclusive row lock within a transaction, helping serialize conflicting updates. Keep transactions short and consider deadlock retries.
You want Eloquent records marked with a deletion timestamp, excluded from normal queries, and restorable later. Which feature is appropriate?
Answer: The SoftDeletes trait and a deleted_at column
SoftDeletes sets deleted_at and excludes such records from normal queries. Use withTrashed() or onlyTrashed() to include them and restore() to recover them.
A database stores is_admin as 0 or 1, but model consumers should always receive a boolean. Which Eloquent setting is appropriate?
Answer: Define is_admin as boolean in the model's casts
Eloquent attribute casting centralizes type conversion when values are read or written, supporting consistent boolean, datetime, array, and other representations.
You want a reusable Eloquent condition for only published articles, defined on the model. Which mechanism fits?
Answer: A local query scope
A local scope defines a reusable query constraint on the model and can be composed through calls such as Article::published().
You need to process millions of rows without loading them all into memory and reduce skipped rows when records change during processing. Which primary-key-oriented method fits?
Answer: chunkById()
chunkById() retrieves batches using an ID cursor, limiting memory use and reducing skip risks associated with offset-based batching while rows are updated.
You want to avoid exposing Eloquent internals directly and centrally control API field names and related-data representation. Which feature fits?
Answer: An API Resource (JsonResource)
API Resources separate transformation of models and collections into JSON, including conditional attributes and relationships that were actually loaded.
For a frequently changing large-list API, you want to avoid growing offsets on deep pages and can provide stable unique ordering. Which option is a candidate?
Answer: cursorPaginate()
Cursor pagination carries the previous position in a cursor and avoids offset scanning. It needs stable unique ordering and is not designed for jumping directly to arbitrary page numbers.
A controller depends on a payment interface whose implementation should differ in production and tests. Where should the mapping normally be registered?
Answer: Bind it in the service container through a Service Provider
Binding an interface to an implementation in a Service Provider lets the service container resolve dependencies and makes substitutions straightforward.
You want the service container to resolve dependencies automatically and reduce direct new calls in a controller. What is the basic approach?
Answer: Type-hint dependencies in the controller constructor or method
When typed dependencies are accepted by a constructor or controller method, the container resolves them, making dependencies explicit and replaceable in tests.
A five-minute aggregate task starts again while its previous run is still active, causing duplicate work. Which Laravel Scheduler option fits?
Answer: withoutOverlapping()
withoutOverlapping() uses a cache lock to prevent overlapping executions of the same scheduled task. Consider lock expiration and multi-server scheduling as well.
A queued job retries immediately during a temporary external API outage, adding more load. Which job settings should be considered?
Answer: Configure a retry limit and backoff
Retry limits and backoff avoid endless retries for permanent failures and space attempts during temporary outages. The job should also be idempotent.
A queued job exceeded its maximum attempts. After investigating and fixing the cause, how is it commonly requeued?
Answer: Inspect the failed job and retry it with queue:retry
Configure failed-job storage and monitoring, inspect the exception, payload, and attempts, then use queue:retry for the selected ID after correcting the cause.
The same business notification should use mail and database channels, selected according to user preferences. Which Laravel mechanism fits?
Answer: Return channels from a Notification class's via() method
Laravel Notifications selects mail, database, and other channels in via() and organizes channel-specific representations in one notification class.
With Laravel's HTTP Client, you want bounded waiting and retries for temporary transport failures. Which combination is a candidate?
Answer: Http::timeout(...)->retry(...)->get(...)
A timeout bounds waiting while retry controls count and delay. Choose retryable failures, idempotency, and total wait time according to requirements.
A private S3 object should be downloadable by an authenticated user for only ten minutes. If the configured disk supports it, which option fits?
Answer: Storage::disk(...)->temporaryUrl(...)
A temporary URL provides time-limited signed access without exposing storage credentials. Application authorization must still be checked first.
In an order API feature test, you want to verify that the correct job was dispatched without running a real queue worker. Which approach fits?
Answer: Use Queue::fake() and Queue::assertPushed()
The queue fake replaces real dispatch and lets tests assert that a selected job was pushed with expected data, avoiding external side effects.
You want short distributed mutual exclusion so multiple servers do not run the same billing task concurrently. Which feature should be considered?
Answer: An atomic lock through Cache::lock()
Cache::lock() with a shared atomic-lock-capable driver can coordinate processes across servers. Design expiration, ownership, and exception release carefully.
A Sanctum personal access token has only the orders:read ability. What is a sound API authorization policy?
Answer: Check the token ability and also authorize access to the specific order through a Policy or equivalent
Token abilities limit API operation scope, but authorization must also verify access to the specific resource. Combine least-privilege abilities with Policies.
During production deployment, normal users should see maintenance mode while a verifier can bypass it with a secret URL. Which option fits?
Answer: php artisan down --secret=...
down --secret enables maintenance mode and can issue a bypass cookie through a secret path. Protect the secret and include php artisan up in deployment.