Laravel
Laravel is the full-stack PHP framework built on a service container, with Eloquent, Blade, queues and the Artisan CLI. Most PHP job postings are Laravel roles, so interviews go deep on it.
on this pageshowhide
explore
- App Setup & Structure33 questions
- Installation & Local Dev5 questions
- Directory Layout5 questions
- Boot & Dispatch Sequence5 questions
- Config Files & Environment6 questions
- Yearly Majors & Support6 questions
- Package Discovery & Publishing6 questions
- Service Container20 questions
- Bindings & Lifetimes5 questions
- Contextual Binding & Attributes5 questions
- Register & Boot Phases5 questions
- Facades vs Injection5 questions
- URL Mapping30 questions
- Route Files & Verbs6 questions
- Path Segments & Regex Rules5 questions
- Named Routes & Groups5 questions
- Link Generation & Signing4 questions
- Implicit & Explicit Binding5 questions
- Named Rate Limiters5 questions
- Endpoint Classes12 questions
- Plain & Single-Action Controllers6 questions
- Resource Controllers6 questions
- Middleware Layers21 questions
- Registration & Priority5 questions
- Handle & Terminate Hooks5 questions
- Default Global Stack6 questions
- CORS Paths & Origins5 questions
- Request Data & Replies37 questions
- Input Retrieval & Old Input6 questions
- Uploaded Files to Disks5 questions
- Session Drivers & Flash5 questions
- Views, JSON & Downloads6 questions
- Redirects & Intended URLs5 questions
- Streamed Output & SSE5 questions
- API Resource Classes5 questions
- Eloquent Models44 questions
- Table Conventions & Mass Assignment5 questions
- Retrieving & Saving Records6 questions
- Relationship Types5 questions
- Querying & Syncing Relations6 questions
- Eager Loading & Strictness6 questions
- Casts, Accessors & Mutators6 questions
- Scopes & Soft Deletes5 questions
- Lifecycle Events & Observers5 questions
- Database Layer28 questions
- Fluent Query Builder6 questions
- Transaction Closures & Connections6 questions
- Blueprints & Migrate Commands5 questions
- Factories & Seeders6 questions
- Paginators & Page Links5 questions
- Cache & Locks11 questions
- Stores & Remember Helpers6 questions
- Atomic Mutexes5 questions
- Blade Views22 questions
- Echo Syntax & Raw Output6 questions
- Conditional & Loop Directives5 questions
- Props, Slots & Attribute Bags5 questions
- Layouts & Stacks6 questions
- Frontend Stack Choices16 questions
- Vite Asset Bundling6 questions
- Official Starter Kits5 questions
- Server-Driven vs SPA UIs5 questions
- Artisan & Dev Tools20 questions
- Built-In Commands & Tinker6 questions
- Custom Console Commands6 questions
- Sail Docker Setup4 questions
- Pint Code Style4 questions
- Validating Incoming Data21 questions
- Form Request Classes5 questions
- Rules & Rule Objects6 questions
- Manual Validators5 questions
- Error Bags & Messages5 questions
- Crypto & Forgery Defenses12 questions
- Encrypter & Key Rotation4 questions
- Password Hash Drivers4 questions
- CSRF Middleware & Tokens4 questions
- Accounts & Access Control47 questions
- Sanctum6 questions
- Passport OAuth Server6 questions
- Gates & Policies6 questions
- Guards & User Providers5 questions
- Fortify Auth Backend6 questions
- Manual Sign-In & Logout6 questions
- Password Reset & Verification6 questions
- Socialite Social Login6 questions
- Errors, Logs & Debugging31 questions
- Report Callbacks & Throttling5 questions
- Exception Rendering & Pages5 questions
- Channels & Stacks6 questions
- Context Data & Formatters5 questions
- Dumps & Debugbar5 questions
- Telescope Watchers5 questions
- Localization11 questions
- Translation Files & Plurals6 questions
- Locale Selection & Switching5 questions
- Queues & Jobs24 questions
- Dispatching & Uniqueness5 questions
- Worker Processes & Backends5 questions
- Retries & Failure Handling5 questions
- Chains & Batches4 questions
- Horizon Supervisors5 questions
- Task Scheduler12 questions
- Schedule Definitions6 questions
- Overlap & One-Server Runs6 questions
- Signals & Outbound Messages25 questions
- Listeners & Subscribers5 questions
- Broadcast Channels & Echo5 questions
- Reverb WebSocket Server5 questions
- Mailables & Mail Drivers5 questions
- Notifiable Delivery Channels5 questions
- Storage Facade11 questions
- Disks & Drivers5 questions
- Reads, Writes & Temporary URLs6 questions
- Automated App Checks27 questions
- Suites, Runner & Parallelism5 questions
- HTTP Feature Assertions5 questions
- Database Reset Traits5 questions
- Fakes, Mocks & Time Travel6 questions
- Dusk Browser Automation6 questions
- Everyday Helpers27 questions
- Chained Collection Methods6 questions
- Generator-Backed Collections5 questions
- Fluent Strings & Dates6 questions
- HTTP Client Facade6 questions
- Processes & Concurrency4 questions
- Shipping & Running24 questions
- Optimize & Cache Commands5 questions
- Health Route & Maintenance4 questions
- Deploy Checklist & Steps5 questions
- Cloud, Forge & Vapor5 questions
- Pulse Dashboards5 questions
- Official Add-Ons15 questions
- Scout Full-Text Search5 questions
- Cashier Billing5 questions
- Pennant Feature Flags5 questions
questions
581 · 25 sectionsIn a Laravel project, what is the difference between .env and .env.example, and which one belongs in version control?
basics
~10 s.env holds this machine's real settings and secrets and is git-ignored; .env.example is the committed template listing every variable the app needs, with placeholder values. Laravel copies .env.example to .env on install.
In a fresh Laravel 13 application, what belongs in app, bootstrap, config, database, public, resources, routes and storage?
basics
~20 sapp holds your classes, bootstrap boots the framework and keeps its caches, config holds settings arrays, database holds migrations, factories and seeders, public is the web root, resources holds views and raw assets, routes the route files, storage runtime files and logs.
In a Laravel 13 app, what does `composer run dev` start, and why use it instead of running `php artisan serve` alone?
basics
~20 scomposer run dev calls php artisan dev, which by default runs the PHP development server, a queue listener, Pail log tailing and the Vite dev server together. artisan serve alone only answers HTTP, so queued jobs and Vite assets are left without a process.
In Laravel 13, how does `laravel new` differ from `composer create-project laravel/laravel` when you start a new application?
basics
~20 scomposer create-project laravel/laravel copies the bare skeleton and runs its Composer scripts (.env, app key, SQLite file, migrations). laravel new wraps that step and adds prompts, an optional starter kit, Pest by default, a front-end build and Boost.
In a Laravel 13 app, what do public/index.php and bootstrap/app.php each do when an HTTP request arrives?
basics
~10 spublic/index.php is the entry point: it checks for maintenance mode, loads Composer's autoloader, requires bootstrap/app.php to get the application, and calls handleRequest(Request::capture()). bootstrap/app.php builds and returns that application with Application::configure()->...->create().
In Laravel, when do you need to register a service container binding, and what can auto-wiring build without one?
basics
~20 sLaravel's container auto-wires any concrete class by reflecting on its constructor type hints. An interface or abstract class needs a binding, or a binding attribute, to an implementation, and a required scalar with no default needs its value supplied.
In Laravel, what is the difference between using the Cache facade, the cache() helper and an injected Illuminate\Contracts\Cache\Repository?
basics
~20 sAll three reach the same container-managed cache service, so behaviour matches. The facade and cache() helper call it from inside method bodies; an injected Repository contract declares the dependency in the constructor, which is explicit and framework-portable.
In a Laravel service provider, what belongs in register() and what belongs in boot(), and why does the order matter?
basics
~20 sregister() should only bind services into the container; boot() configures the app with them, such as macros, view composers, gates and event listeners. Laravel runs every provider's register() before any boot(), so boot() can rely on every registered service.
In Laravel's service container, how do bind(), singleton(), scoped() and instance() differ in what repeated resolutions return?
basics
~20 sbind() builds a new object on every resolution; singleton() builds once, lazily, and returns that object afterwards; scoped() is a singleton forgotten when a queue job or Octane request starts; instance() stores an object you already built.
In Laravel, how does a call like Cache::get('key') reach a real object when the Cache facade class defines no static get method?
basics
~10 sCache extends Illuminate\Support\Facades\Facade, whose __callStatic() catches the missing static call, resolves the container binding named by getFacadeAccessor() ('cache', a CacheManager) and calls get() on that object.
In Laravel, how does implicit route model binding turn the {task} segment of /tasks/{task} into a Task model, and what happens when no row matches?
basics
~20 sWhen an action type-hints an Eloquent model and names the variable after the route segment, Laravel queries that model by its route key (the primary key by default) and injects it. No matching row throws ModelNotFoundException, rendered as a 404.
In Laravel, how do you name a route with ->name() and build its URL with route(), including parameters and extra query keys?
basics
~10 sChain ->name('franchise.orders.show') on the route, then call route('franchise.orders.show', ['order' => 42]); matching keys fill the placeholders, leftover keys become the query string, and the URL is absolute unless the third argument is false.
In Laravel, how do you declare required and optional route parameters, and what must the handler supply for an optional one?
basics
~20 sWrap a URI segment in braces, {year}, to capture it, and add a question mark, {month?}, to make it optional; the handler argument for an optional segment needs a default value, such as ?string $month = null.
In Laravel, which HTTP verbs do Route::get, Route::match and Route::any register, and how do you confirm them?
basics
~20 sRoute::get registers GET and HEAD; post, put, patch, delete and options register one verb each; Route::match registers the verbs you list (plus HEAD when GET is listed); Route::any registers all seven router verbs. php artisan route:list shows each route's verbs, URI, name and action.
In a Laravel 13 app, how do routes/web.php and routes/api.php differ, and why does a new app have no api.php?
basics
~10 sroutes/web.php is loaded inside the web middleware group for browser pages with sessions and CSRF protection; routes/api.php, created by php artisan install:api, is loaded inside the stateless api group under an automatic /api prefix.
In Laravel 13, what does php artisan make:controller generate, and how does a route reach one of that controller's methods?
basics
~20 smake:controller writes a class into app/Http/Controllers whose public methods are actions. A route targets one with the array [CarController::class, 'show']; on a match Laravel builds the controller through the container and calls that method with the route parameters.
In Laravel, which routes does Route::resource('books', BookController::class) register, with their HTTP verbs, URIs, actions and route names?
basics
~10 sRoute::resource('books', ...) registers seven routes: GET /books (index), GET /books/create (create), POST /books (store), GET /books/{book} (show), GET /books/{book}/edit (edit), PUT/PATCH /books/{book} (update) and DELETE /books/{book} (destroy), named books.index and so on.
In a Laravel 13 controller, how does implementing HasMiddleware assign middleware, and how do Middleware only and except narrow it?
basics
~10 sA controller implementing HasMiddleware defines a static middleware() method returning middleware names, closures or Middleware objects; new Middleware('log', only: ['index']) limits one to listed methods and except excludes methods. It replaces constructor $this->middleware() calls.
In Laravel, what does Route::apiResource change compared with Route::resource, and how do only() and except() narrow a resource?
basics
~20 sRoute::apiResource registers the resource routes minus the create and edit form pages, leaving index, store, show, update and destroy. only([...]) keeps just the listed actions and except([...]) removes listed ones; make:controller --api stubs the matching five methods.
In a new Laravel 13 app, what does the base App\Http\Controllers\Controller contain, and why do $this->authorize() and $this->validate() fail there?
basics
~20 sThe base Controller in a Laravel 13 skeleton is an empty abstract class: no parent, no AuthorizesRequests or ValidatesRequests traits. $this->authorize() and $this->validate() are undefined unless you add those traits back; the usual replacements are Gate::authorize() and $request->validate().
In Laravel, what does php artisan make:middleware generate, and how does the generated handle() method let a request through or stop it?
basics
~10 smake:middleware creates a class in app/Http/Middleware with handle(Request $request, Closure $next): Response. Returning $next($request) passes the request inward; returning your own response, such as a redirect, stops it before the controller runs.
In a fresh Laravel 13 app with no config/cors.php, what answers CORS requests, and how do you change its settings?
basics
~20 sLaravel's HandleCors middleware answers CORS requests: it sits in the default global stack and reads the cors config. A new app runs on the framework's built-in defaults until you run php artisan config:publish cors and edit config/cors.php.
In Laravel 13, which middleware does the web group run that the api group does not, and why does an API route have no session?
basics
~10 sThe web group adds EncryptCookies, AddQueuedCookiesToResponse, StartSession, ShareErrorsFromSession and PreventRequestForgery before SubstituteBindings; the api group has only SubstituteBindings. API routes therefore never start a session, decrypt cookies or check CSRF tokens.
In Laravel 13, where do you register a custom middleware to run on every request, and how does that differ from attaching it to routes?
basics
~10 sGlobal middleware is registered in bootstrap/app.php inside withMiddleware(), using $middleware->append() or prepend(); it wraps every request before routing. Route middleware is attached with ->middleware() on a route or group, by class name or alias.
In a Laravel food-ordering app, how would you write a middleware that times each request, adds the duration to the response, and logs slow ones?
basics
~10 sRecord hrtime(true) before calling $next, store $response = $next($request), compute the elapsed milliseconds, set a header on $response, call Log::warning() when it exceeds a threshold, and return the response.
In Laravel, what is an API resource class such as a JsonResource, and why return one instead of the Eloquent model itself?
basics
~20 sAn API resource is a class extending JsonResource whose toArray() maps one model to the exact JSON the API promises, so column renames, new columns and internal fields do not leak into responses by accident.
In a Laravel controller, how do $request->input(), query(), all(), only() and except() differ when reading a search form?
basics
~20 sinput() reads a field from the request body and query string together (body wins on a clash) and follows dot paths; query() reads only the query string; all() returns every field plus uploaded files; only() and except() return a filtered subset.
In Laravel, how do redirect()->to(), redirect()->route(), to_route(), back() and redirect()->away() differ, and which status do they send?
basics
~20 sAll five return an Illuminate\Http\RedirectResponse with status 302 unless you pass another code. to() takes a path or URL, route() and to_route() a route name, back() the previous page, and away() an external URL used as-is.
In a Laravel route or controller, what response does the framework build when you return a string, an array, an Eloquent model or a view?
basics
~20 sLaravel's router wraps the return value: a string or view becomes an HTML response with status 200, while arrays, Eloquent models and collections become a JsonResponse. A model created during the request returns 201 instead of 200.
In Laravel, how do you store, read and remove session data with get(), put(), push(), pull() and forget()?
basics
~20 sThrough $request->session(), the session() helper or the Session facade: put() stores a value, get() reads it with an optional default, push() appends to an array value, pull() reads and removes in one call, and forget() deletes keys; flush() empties the session.
In a Laravel 13 Eloquent model, what does casts() declare, how does it relate to $casts, and what do common built-in casts return?
basics
~20 scasts() returns a map of attribute names to cast types such as boolean, datetime, decimal:2, enum classes and cast classes, applied on every read and write. The older $casts property still works; casts() is merged over it and can call static helpers.
In Laravel's Eloquent, which table, primary key and timestamp columns does a model assume by convention, and how do you override them?
basics
~20 sEloquent assumes the snake_case plural of the class name as the table, an auto-incrementing integer id key, and managed created_at and updated_at columns. Override them with the $table, $primaryKey, $keyType, $incrementing and $timestamps properties, or Laravel 13's #[Table] attribute.
In Eloquent, what do find(), findOrFail(), first() and firstWhere() return when no matching row exists?
basics
~10 sfind(), first() and firstWhere() return null when nothing matches, while findOrFail() and firstOrFail() throw ModelNotFoundException. Choose the null-returning form when absence is normal and the OrFail form when absence is an error.
In a Laravel blog index, how does Post::with('author') stop a Blade loop printing $post->author->name from running one query per post?
basics
~20 sPost::with('author') runs the posts query, then one extra query that fetches every needed author by id and attaches each to its post. The Blade loop then reads already-loaded authors: two queries instead of one per post.
In a fresh Laravel 13 app, which database connection is used by default, where is that decided, and how do you run a query on another named connection?
basics
~10 sSQLite: config/database.php sets 'default' => env('DB_CONNECTION', 'sqlite') and the skeleton's .env.example sets DB_CONNECTION=sqlite, pointing at database/database.sqlite. DB::connection('pgsql') returns any other connection named in the 'connections' array.
In a Laravel model factory, what is the difference between make() and create(), and what does each return?
basics
~20 smake() builds model instances from the factory's definition() without saving them; create() builds them the same way and then persists each one with save(). Both return a single model, or an Eloquent Collection once count() is set.
In Laravel, how do you organise and run database seeders, and what do db:seed --class and migrate --seed do?
basics
~20 sA seeder is a class in database/seeders with a run() method; DatabaseSeeder is the root and runs others through $this->call(). php artisan db:seed runs DatabaseSeeder, --class runs one seeder, and migrate --seed seeds after migrating.
In Laravel, what does php artisan make:migration create_listings_table generate, and how do its up() and down() methods relate to migrate and migrate:rollback?
basics
~20 sIt writes a timestamped file in database/migrations that returns an anonymous class extending Migration, with up() creating the listings table and down() dropping it. migrate runs pending up() methods as one batch; migrate:rollback runs down() for the last batch.
In Laravel, what is the difference between paginate(), simplePaginate() and cursorPaginate(), and which SQL queries does each run?
basics
~20 spaginate() runs a COUNT query plus a LIMIT/OFFSET query and returns a LengthAwarePaginator with totals and page numbers; simplePaginate() runs one LIMIT/OFFSET query for next/previous only; cursorPaginate() filters on the ordered columns instead of using an offset.
In Laravel, how do Cache::lock()'s get() and block() differ when two queue workers try to generate the same monthly statement at once?
basics
~10 sCache::lock($name, $seconds)->get() tries once and returns true or false immediately; block($wait) keeps retrying and throws LockTimeoutException after $wait seconds. Both accept a closure and release the lock automatically when it finishes.
In Laravel, how does Cache::remember() cache an expensive exchange-rate lookup, and what happens on a cache hit versus a miss?
basics
~20 sCache::remember($key, $ttl, $closure) returns the cached value when the key exists; on a miss it runs the closure, stores the result for the TTL (integer seconds or a DateTime) and returns it, so the expensive lookup runs once per TTL window.
In Laravel 13, which cache store does a fresh app use, how does CACHE_STORE select it, and how does the failover store behave?
basics
~20 sA Laravel 13 skeleton uses the database store: CACHE_STORE in .env feeds the default key of config/cache.php, which names one entry in its stores array. The failover store tries its listed stores in order and moves on only when one throws.
In Laravel 13, which cache stores can back Cache::lock() across servers, and where do the database and Redis stores keep their locks?
basics
~20 sCross-server locks need a shared store: database, redis, memcached or dynamodb; file covers one machine and array one process. The Laravel 13 database default uses the cache_locks table; Redis uses its lock_connection, the default connection.
In Laravel, how do you acquire a Cache::lock() in a controller and release it from the queued job it dispatches, using owner() and restoreLock()?
basics
~10 sAcquire the lock in the controller, pass $lock->owner() into the job, and inside the job call Cache::restoreLock($name, $owner)->release(). The restored object carries the same owner token, so its owner-checked release() succeeds.
In Laravel Blade, what is the difference between a class-based component and an anonymous component, and when would you choose each?
basics
~20 sA class-based component pairs a PHP class in app/View/Components with a view and takes props through its constructor; an anonymous component is just a Blade file in resources/views/components using @props. Pick a class for logic or injected services.
Inside a Blade @foreach, what does $loop provide, and how would you use it to mark a pricing table's first, last and alternating rows?
basics
~10 sBlade sets a $loop object on every @foreach iteration with index (from 0), iteration (from 1), count, remaining, first, last, odd, even, depth and parent, so rows can be styled without a hand-kept counter.
In a Blade view, what is the difference between {{ $value }} and {!! $value !!}, and when is the raw form acceptable?
basics
~20 sBlade compiles {{ $value }} to an echo through the e() helper, which runs htmlspecialchars so markup prints as text; {!! $value !!} echoes the value untouched, so it is safe only for HTML your own code built or sanitized.
In Laravel Blade, how does a layout component with {{ $slot }} differ from an @extends layout, and which suits a new app?
basics
~20 sA layout component wraps the page: markup between <x-layout> tags lands in the component's {{ $slot }}. An @extends layout is inheritance: the child fills @section blocks that the layout prints with @yield. New apps usually choose components.
In a Blade component, how does $attributes->merge() treat class compared with other attributes, and when do you need class() or prepends()?
basics
~20 smerge() adds default attributes: class and style defaults are joined with the caller's values, while any other default is replaced by the caller's value. class() adds classes conditionally; prepends() makes a non-class default join instead.
Which official starter kits does Laravel 13 offer, and what does each one give a brand-new application?
basics
~20 sLaravel 13 offers React, Vue and Svelte kits built on Inertia with TypeScript, Tailwind and a shadcn component library, and a Livewire kit with Flux UI. Each creates a full app with Fortify-backed login, registration, password reset, 2FA and settings pages.
In a Laravel Blade layout, what does the @vite directive output, and how does that differ between npm run dev and npm run build?
basics
~20 s@vite prints the script and stylesheet tags for the entry points you name. With npm run dev it points them at the Vite dev server (plus the @vite/client HMR script); after npm run build it reads public/build/manifest.json and links the hashed, compiled files.
What does it mean in practice that a Laravel starter kit's code is yours, and how do you keep a starter-kit app up to date?
basics
~20 sA starter kit copies a whole application into your repository; there is no kit package to update. You edit its screens, actions and routes freely and keep the underlying packages (framework, Fortify, Inertia or Livewire, Flux) current with Composer and npm.
In Laravel, how do Blade, Livewire, Inertia and a separate SPA on a JSON API differ in routing ownership and where UI state lives?
basics
~20 sBlade, Livewire and Inertia all keep routing in Laravel's route files and controllers; only a separate SPA moves routing into a client-side router over a JSON API. UI state lives in the server render (Blade), a component snapshot (Livewire), or client components (Inertia, SPA).
How does Laravel's Vite class choose between the dev server and built assets, and what breaks when public/hot or the manifest is wrong?
basics
~20 sLaravel's Vite class calls isRunningHot(), which is just is_file() on public/hot. If the file exists, every tag points at the URL inside it; otherwise tags come from public/build/manifest.json. A stale hot file or a missing manifest breaks every page.
In Laravel, how do `php artisan list`, `php artisan help` and `php artisan about` help you get oriented in an unfamiliar application?
basics
~10 sphp artisan list prints every registered command grouped by namespace, php artisan help <command> shows one command's arguments and options, and php artisan about summarises versions, environment, debug mode, cache status and drivers.
In Laravel, what do the `make:*` Artisan generators do, and what does `php artisan make:model Shipment -a` create?
basics
~10 smake:* commands generate boilerplate classes from stub templates into the conventional folders. make:model Shipment -a also creates a migration, factory, seeder, policy and a resource controller wired to StoreShipmentRequest and UpdateShipmentRequest.
In Laravel 13, how do you create a custom Artisan command with `make:command`, and how are its signature, description and `handle()` wired up?
basics
~10 sphp artisan make:command ResendFailedInvoices writes a class to app/Console/Commands, which Laravel registers automatically. Its #[Signature] attribute names the command and declares input, #[Description] feeds the listing, and handle() does the work with container-injected services.
What is Laravel Pint, and how do you run it to fix the code style of a Laravel application?
basics
~20 sLaravel Pint is an opinionated PHP code style fixer built on PHP CS Fixer and shipped as a dev dependency of new Laravel apps. Running ./vendor/bin/pint rewrites your PHP files to the laravel preset; adding --test only reports.
What is Laravel Sail, and how do you add it to a Laravel 13 application and start its containers?
basics
~20 sLaravel Sail is a bash script plus a generated compose.yaml that runs the app and its services in Docker. In Laravel 13 you run composer require laravel/sail --dev, then php artisan sail:install, then ./vendor/bin/sail up.
In a Laravel 13 controller, what does $request->validate() return on success, and what happens when validation fails?
basics
~20 s$request->validate($rules) returns an array of just the validated fields. On failure it throws ValidationException, which becomes a redirect back with flashed errors and old input, or a 422 JSON response when the request expects JSON; the rest of the action never runs.
In a Laravel Blade view, how do you show validation errors after a failed form submission, and where does the $errors variable come from?
basics
~20 sA failed form validation redirects back and flashes the errors to the session; ShareErrorsFromSession in the web group shares them with every view as $errors, a ViewErrorBag. Read them with @error('field') and $message, or first(), has() and all().
In Laravel, what is a form request class, and when does it authorize and validate the request relative to your controller method?
basics
~20 sA form request is a class extending Illuminate\Foundation\Http\FormRequest that carries authorize() and rules(). When the container resolves it for a type-hinted controller parameter, it authorizes and validates first; the action body runs only if both pass.
In Laravel, when would you use Validator::make() instead of $request->validate(), and how do fails(), validate() and validated() differ?
basics
~20 sValidator::make($data, $rules) validates any array and does nothing on failure until you ask. fails() returns a boolean and fills errors(); validate() throws ValidationException or returns the validated array; validated() returns the validated data and also throws if invalid.
In Laravel, where can you override a validation error message or the :attribute name, and in what order does the validator look for them?
basics
~20 sPass inline messages and attribute names (a form request's messages() and attributes(), or the extra validator arguments) or put them in lang/{locale}/validation.php under custom and attributes. Inline entries win, then custom, then the rule's default line.
In a Laravel 13 Blade form, what does @csrf add, and when does a POST without a valid token fail with a 419 error?
basics
~20 s@csrf renders a hidden _token input holding the session's CSRF token. In Laravel 13, PreventRequestForgery lets same-origin browser requests through by Sec-Fetch-Site; otherwise a missing or stale token throws TokenMismatchException, rendered as 419 Page Expired.
In Laravel, what is APP_KEY, what does php artisan key:generate write, and what happens when the key is missing?
basics
~20 sAPP_KEY is the secret the Laravel encrypter, encrypted cookies and signed URLs use. key:generate writes a random key (32 bytes for the default cipher), base64-encoded behind a base64: prefix, into .env; with no key, resolving the encrypter throws MissingAppKeyException.
In Laravel, how do Hash::make() and Hash::check() store and verify a password, and why is Crypt::encryptString() the wrong tool for it?
basics
~20 sHash::make() turns a password into a one-way, salted bcrypt or Argon2 hash that you store; Hash::check() re-hashes the attempt and compares, returning true or false. Crypt is reversible, so anyone with APP_KEY could read every password.
A payment provider's webhook POST to your Laravel 13 app gets 419 responses; why, and how do you exempt that route correctly?
basics
~20 sRoutes in routes/web.php run PreventRequestForgery, and a server-to-server webhook sends neither Sec-Fetch-Site nor a CSRF token, so it gets 419. Exempt the URI with preventRequestForgery(except:) or move the route outside the web group, then verify the provider's signature.
A telehealth platform's Laravel APP_KEY has leaked; how do you rotate it with APP_PREVIOUS_KEYS, and what stays exposed until the old key is retired?
basics
~20 sSet a new APP_KEY and list the leaked one in APP_PREVIOUS_KEYS so sessions, stored ciphertext and signed links keep working. New values use the new key, but anything forged with the leaked key still verifies until you re-encrypt data and remove it.
In Laravel, what is the difference between a gate defined with Gate::define and a policy class, and when would you choose each?
basics
~20 sA gate is a named closure registered with Gate::define for one-off checks not tied to a model. A policy is a class grouping one model's abilities (view, update, delete), found from the model you pass; most model rules belong there.
In Laravel's config/auth.php, what is the difference between a guard and a user provider, and what ships by default?
basics
~20 sA guard decides how a request is authenticated and remembered; a user provider decides where user records are loaded from. The Laravel 13 skeleton ships one web guard (session driver) pointing at one users provider (eloquent, App\Models\User).
In Laravel, how does a hand-built login use Auth::attempt, and why does the documented example call $request->session()->regenerate() afterwards?
basics
~20 sAuth::attempt($credentials) finds the user by the non-password keys, checks the password hash and, on success, signs them into the session, returning true or false. Regenerating the session ID defeats session fixation; Laravel 13's guard already does it in login().
In Laravel, what must be in place for the verified middleware to keep users with unconfirmed email addresses out of a route?
basics
~10 sApp\Models\User must implement Illuminate\Contracts\Auth\MustVerifyEmail, users needs an email_verified_at column, sign-up must dispatch Registered, the verification.notice, verification.verify and verification.send routes must exist, and routes use ['auth', 'verified'].
What two authentication mechanisms does Laravel Sanctum provide, and which one suits a first-party SPA versus a mobile app?
basics
~20 sSanctum offers cookie-based session authentication for a first-party SPA on a stateful domain, and database-backed personal access tokens sent as a Bearer header for mobile apps and scripts. Your own SPA uses the session; the mobile app uses a token.
Why must APP_DEBUG be false on a production Laravel app, and what does the debug exception page reveal when it is true?
basics
~20 sWith APP_DEBUG=true an unhandled error renders Laravel's detailed exception page: stack frames with source code, request headers and body, route details and executed SQL. On a public site that hands attackers secrets and internals, so production keeps it false.
In Laravel, what is the difference between the dump() and dd() helpers, and when is Log::debug() the better choice?
basics
~20 sdump() prints its arguments and lets the request continue; dd() prints them and stops execution. Log::debug() writes to the log instead of the output, so it suits queued jobs, JSON endpoints and anything whose output you cannot see.
In Laravel, how do you give a web app branded error pages for 404 and other HTTP errors, and how do the 4xx and 5xx fallback views work?
basics
~20 sCreate resources/views/errors/404.blade.php (any status code works); Laravel renders it for an HTTP exception with that status and passes it as $exception. 4xx.blade.php and 5xx.blade.php only cover statuses with no specific page, yours or the framework's.
In Laravel, what does the report() helper do, and when would you call it instead of letting an exception propagate?
basics
~20 sreport($e) passes a Throwable to Laravel's exception handler, which applies its filters, throttling, callbacks and default logging, then returns so your code carries on. Call it in a catch block when a failure must be recorded without failing the request.
In a Laravel 13 app, what do LOG_CHANNEL, LOG_STACK and LOG_LEVEL control, and where do log entries go by default?
basics
~10 sLOG_CHANNEL picks the default channel (stack), LOG_STACK lists the channels that stack writes to (single), and LOG_LEVEL is the minimum level for channels that read it (debug). So Log::info() lands in storage/logs/laravel.log.
In Laravel 13, where is the application's default locale configured, and how do you switch the locale for the current request?
basics
~10 sThe default is the locale key in config/app.php, read from APP_LOCALE and defaulting to en. App::setLocale('es') switches it for the rest of the current request; App::currentLocale() and App::isLocale('es') read it back.
In Laravel, how do you define a translation line in lang/{locale}/messages.php and read it with __(), and what comes back when the key is missing?
basics
~10 sCreate lang/{locale}/messages.php returning a keyed array and call __('messages.welcome'). If neither the current nor the fallback locale has that line, __() returns the key string itself instead of throwing.
On a multinational Laravel HR portal, how would you apply each employee's saved language on every request, falling back to the browser's Accept-Language?
basics
~10 sWrite a middleware that takes $request->user()?->locale when it is supported, else $request->getPreferredLanguage($supported), and calls App::setLocale(). Append it to the web group so it runs after the session starts and the employee is known.
In Laravel, when would you keep translations in lang/es.json rather than lang/es/*.php group files, and how does __() decide which one to read?
basics
~20 sUse lang/es.json, keyed by the original sentence, for many UI strings; use PHP group files for stable short keys and nested arrays. __() checks the locale's JSON file first, then parses the key as group.item.
In a Laravel translation string, how are :name, :Name and :NAME placeholders filled, and what happens to a placeholder you do not pass?
basics
~20 sPass an array as the second argument, __('messages.thanks', ['name' => 'ana']). Laravel replaces :name as given, :Name with the first letter uppercased and :NAME fully uppercased; a placeholder with no value stays in the output literally.
In Laravel, what is the difference between Bus::chain and Bus::batch, and when would you use each for queued jobs?
basics
~20 sBus::chain runs jobs one after another, each only if the previous one succeeded, and stops at the first failure. Bus::batch pushes all jobs at once to run in parallel, records progress in job_batches and fires then, catch and finally callbacks.
In Laravel, how do you create a queued job with make:job and dispatch it so it runs on a worker instead of inside the request?
basics
~20 sRun php artisan make:job to get a class in app/Jobs that implements ShouldQueue and uses the Queueable trait, then call YourJob::dispatch($args). The job is serialized onto the default connection (database in a new app) and a queue:work process later calls handle().
In Laravel, which Artisan commands list, retry and delete failed queued jobs, and what does queue:retry actually do with a failed job?
basics
~10 sphp artisan queue:failed lists failed_jobs, queue:retry <id> or all pushes the stored payload back onto its original queue, queue:forget <id> deletes one record, queue:flush deletes all, and queue:prune-failed removes old ones.
In Laravel, what is the difference between php artisan queue:work and php artisan queue:listen, and which belongs in production?
basics
~20 squeue:work boots the app once and runs jobs in one long-lived process: fast, but blind to new code until restarted. queue:listen spawns a fresh queue:work --once per job: current code, much slower. Production runs queue:work.
In Laravel, why can a job dispatched inside DB::transaction during sign-up fail on the worker, and how does afterCommit fix it?
basics
~20 sThe job can reach a worker before the transaction commits, so the worker cannot see the new user and SerializesModels throws ModelNotFoundException. afterCommit holds the push until every open transaction commits, and drops the job on rollback.
In Laravel 13, where do you define scheduled tasks, and how does a single cron entry running schedule:run execute all of them?
basics
~20 sTasks are registered with the Schedule facade in routes/console.php, or through withSchedule in bootstrap/app.php. One server cron entry runs php artisan schedule:run every minute, and that command runs whichever tasks are due in that minute.
In Laravel's scheduler, how do Schedule::command, Schedule::job, Schedule::call and Schedule::exec differ, and in which process does each task's work run?
basics
~20 sSchedule::command and Schedule::exec start a child process from schedule:run; Schedule::call runs a closure inside the schedule:run process; Schedule::job dispatches the job, so a ShouldQueue job runs later on a queue worker, while a non-queued one runs inline.
In Laravel's scheduler, what does withoutOverlapping() do, where is its lock stored, and how long does that lock last by default?
basics
~20 swithoutOverlapping() makes the scheduler take a cache lock before running a task and skip the task while that lock exists, so a slow run is not joined by a second copy. The lock expires after 1440 minutes unless you pass another value.
When a Laravel app scaled to three servers runs schedule:run on each, why does a report task run three times, and how does onOneServer() prevent it?
basics
~20 sEach server's cron runs schedule:run, and each sees the same task due, so it runs once per server. onOneServer() makes each server try a lock in a shared cache keyed by task and minute; only the winner runs it.
In Laravel's scheduler, do tasks due in the same minute run in parallel, and what changes when you add runInBackground() to one?
basics
~10 sNo: schedule:run runs due tasks one after another, in the order they are defined. runInBackground() starts a command or exec task as a detached process and moves on at once; closures cannot use it.
In Laravel 13, what steps does it take to broadcast a server-side event such as BidPlaced so that browsers receive it through Echo?
basics
~20 sRun php artisan install:broadcasting, implement ShouldBroadcast on the event with a broadcastOn() returning its channels, dispatch it as usual with a queue worker running, and subscribe in the browser with Echo's channel()->listen() or a useEcho hook.
In Laravel 13, how do you create an event and a listener with Artisan, and how does the framework connect the listener to its event?
basics
~10 sRun make:event OrderPlaced and make:listener ReserveInventory --event=OrderPlaced. Laravel 13 discovers listeners in app/Listeners and registers each handle* or __invoke method for the event class type-hinted on its first parameter; Event::listen registers one by hand.
In Laravel, what do a mailable's envelope(), content() and attachments() methods define, and how do you send that mailable to a customer?
basics
~10 sA mailable, generated by make:mail, splits one email into envelope() for subject and sender metadata, content() for the Blade or Markdown view, and attachments() for files; Mail::to($customer)->send(new OrderConfirmed($order)) delivers it.
In Laravel, what does a notification class contain, how does its via() method pick delivery channels, and how do you send it?
basics
~20 sA notification, made with make:notification, is one message with a format per channel: via() returns the channel names for each recipient, and toMail(), toDatabase() or toVonage() build each version. Send it with $user->notify(...) or Notification::send($users, ...).
What is Laravel Reverb, how does it sit between a Laravel app and Echo, and why does it speak the Pusher protocol?
basics
~20 sReverb is Laravel's first-party WebSocket server, run as a long-lived php artisan reverb:start process. It implements the Pusher protocol, so Laravel broadcasts to it through the Pusher driver and browsers connect with Echo and pusher-js, identified by REVERB_APP_KEY.
In Laravel, what is the public disk, and why do its files return 404 in the browser until you run php artisan storage:link?
basics
~20 sThe public disk is a local-driver disk rooted at storage/app/public for files meant to be web-visible. The web server only serves the public/ directory, so php artisan storage:link creates a public/storage symlink that exposes that folder.
In Laravel, what do Storage::put(), get(), exists() and delete() return on success and failure, and what does a disk's throw option change?
basics
~20 sput(), delete(), copy() and move() return true or false; get() returns the contents or null; exists() returns a boolean. With a disk's throw option true, failures raise League\Flysystem exceptions such as UnableToWriteFile instead of returning false or null.
In Laravel, how do FILESYSTEM_DISK and Storage::disk() pick the disk a Storage call writes to, and what does moving uploads to S3 require?
basics
~20 sStorage calls without disk() go to the default disk, config filesystems.default, read from FILESYSTEM_DISK and falling back to local. Storage::disk('s3') picks a named disk. Moving to S3 needs the Flysystem S3 package, AWS credentials and bucket settings.
In Laravel, when do you use Storage::url() versus Storage::temporaryUrl(), for example for private medical documents that should download for ten minutes?
basics
~10 sStorage::url() builds a permanent, unsigned link that works only for publicly readable files. Storage::temporaryUrl($path, now()->addMinutes(10)) builds a signed link that expires, which suits private medical documents once the user has been authorized.
In Laravel's s3 disk configuration, what do AWS_ENDPOINT, AWS_USE_PATH_STYLE_ENDPOINT and AWS_URL change when the disk points at an S3-compatible service?
basics
~20 sAWS_ENDPOINT feeds the s3 disk's endpoint key, sending API calls to another S3-compatible host. AWS_USE_PATH_STYLE_ENDPOINT puts the bucket in the URL path instead of the hostname. AWS_URL sets the base URL Laravel uses for public file links.
In Laravel, what does the RefreshDatabase trait do to the test database, and why is it the usual default for feature tests?
basics
~20 sRefreshDatabase runs migrate:fresh the first time a test in the process needs it, then wraps every test in a database transaction that is rolled back afterwards. Each test starts from the same clean schema without paying for a migration per test.
In a Laravel feature test, how do you request a sneaker shop's checkout routes and assert the status, redirect and view data?
basics
~10 sCall $this->get() or $this->post() inside a Tests\TestCase test; each returns a TestResponse. Chain assertOk() or assertStatus(), assertRedirect() or assertRedirectToRoute(), and assertViewIs() or assertViewHas() for the Blade data.
In a Laravel 13 app, how do tests in tests/Feature differ from tests in tests/Unit, and which base class does each extend?
basics
~10 sFeature tests extend Tests\TestCase, which boots the whole Laravel application before every test, so HTTP calls, the database, facades and the container work. The skeleton's unit tests extend PHPUnit\Framework\TestCase directly and boot nothing.
In a Laravel feature test, how do you assert that issuing a refund queues a job and sends a mailable without running or sending either?
basics
~10 sCall Queue::fake() (or Bus::fake()) and Mail::fake() before the request, then assert with Queue::assertPushed(ProcessRefund::class) and Mail::assertSent(RefundIssued::class). The fakes record instead of pushing or delivering, so neither the job nor the mail runs.
In a Laravel feature test, what does actingAs($user) do, and how does it differ from logging in through the login route?
basics
~20 sactingAs($user) puts the user straight onto a guard and makes it the default for the rest of the test, skipping credentials, session login and the Login event. Use it for what sits behind login; test login itself through the login route.
In Laravel, what does collect() return, and does chaining map() and filter() on it change the original collection?
basics
~10 scollect() wraps an array or iterable in an Illuminate\Support\Collection. map() and filter() each return a new Collection and leave the original untouched, which is what makes long chains safe to write.
In Laravel's HTTP client, does Http::get() throw an exception when the server answers 404 or 500, and how do you make it throw?
basics
~10 sNo. Laravel's Http client returns a Response for 4xx and 5xx statuses; check successful() or failed(), or call throw() to raise RequestException. Timeouts and refused connections are different: they always throw ConnectionException.
In Laravel, what is the difference between a Collection and a LazyCollection, and when would you reach for the lazy one?
basics
~20 sA Collection holds every item in a PHP array; a LazyCollection holds a source, usually a generator function, and pulls items one at a time only when enumerated. Use it when the data is too big for memory.
In Laravel, what does Process::run() return when an external thumbnail command exits with a non-zero code, and how do you turn that into an exception?
basics
~10 sProcess::run() returns an Illuminate\Process\ProcessResult whatever the exit code: failed() is true and exitCode() holds the code. Chain throw() to raise ProcessFailedException. Running past the 60-second default timeout always throws ProcessTimedOutException.
In Laravel, what do now() and today() return, and how do you show an order's age as '3 days ago' with Carbon?
basics
~10 snow() returns a Carbon instance for the current moment and today() one for midnight today, both created through the Date facade. $order->created_at->diffForHumans() renders a past date relative to now, such as '3 days ago'.
What are the core steps of a Laravel 13 production deploy script, in order, and why do composer install and migrate need --no-dev and --force?
basics
~20 sFetch the code, run composer install --no-dev, build front-end assets, run php artisan migrate --force, run php artisan optimize, then php artisan reload. --no-dev skips require-dev packages; --force skips migrate's production confirmation, which a non-interactive script would otherwise cancel.
In the Laravel ecosystem, how do Laravel Cloud, Laravel Forge and Laravel Vapor differ in who runs the servers your app lives on?
basics
~20 sLaravel Cloud runs the app for you on fully managed, auto-scaling compute with managed databases, caches and object storage; Forge provisions and manages servers you own on a provider; Vapor deploys the app serverless onto AWS Lambda.
In Laravel 13, what does php artisan down do to incoming requests, and how do --secret and --with-secret let the team keep using the site?
basics
~20 sphp artisan down makes Laravel answer requests with a 503 maintenance response. With --secret=token (or a random --with-secret), visiting /token sets a signed laravel_maintenance bypass cookie so that browser uses the site normally; php artisan up ends maintenance.
In Laravel 13, what does php artisan optimize cache, and what does php artisan optimize:clear remove?
basics
~10 sphp artisan optimize runs config:cache, event:cache, route:cache and view:cache, plus any commands packages register. php artisan optimize:clear runs the matching :clear commands, and it also runs cache:clear and clear-compiled.
After installing Laravel Pulse, why does the /pulse dashboard return 403 in production, and how do you grant access to it?
basics
~20 sPulse registers a default viewPulse gate that only passes in the local environment, and its Authorize middleware checks that gate on /pulse, so production answers 403. Define viewPulse yourself in AppServiceProvider::boot, for example allowing only admins.
What is Laravel Cashier (Stripe) for, and what does adding the Billable trait to the User model give you?
basics
~20 sLaravel Cashier wraps Stripe's billing API for an Eloquent model. The Billable trait adds customer columns, a subscriptions relation and methods such as newSubscription(), subscribed(), checkout(), charge() and invoices(), while Stripe remains the system that actually bills customers.
In Laravel Pennant, how do you define a feature with Feature::define(), check it with Feature::active(), and what scope is used by default?
basics
~10 sFeature::define('new-checkout', fn (User $user) => ...) registers a resolver, usually in AppServiceProvider::boot(). Feature::active('new-checkout') checks it for the default scope, the authenticated user, and Feature::for($scope) checks another user, team or value.
In Laravel Scout, what does adding the Searchable trait to an Eloquent model do, and how does its search index stay in sync?
basics
~20 sThe Searchable trait registers a Scout model observer that upserts the record into the search index on every Eloquent save and removes it on delete, using toSearchableArray() as the document and searchableAs() as the index name.
In Laravel Cashier, how does newSubscription(...)->checkout() start a subscription, and when does the local subscriptions row appear?
basics
~20 snewSubscription('default', $priceId) returns a SubscriptionBuilder whose checkout() creates a Stripe Checkout session and redirects there. The local subscriptions row is written later, when Cashier's webhook handler receives customer.subscription.created, not when the customer returns to success_url.
In Laravel Cashier, how do swap(), cancel(), cancelNow() and resume() change a subscription, and what do onTrial() and onGracePeriod() report?
basics
~20 sswap() moves to new prices, prorating by default. cancel() sets ends_at to the period end, leaving a grace period; cancelNow() ends it at once; resume() works only inside the grace period. onTrial() and onGracePeriod() compare trial_ends_at and ends_at with now.