skip to content

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 pageshow

explore

questions

581 · 25 sections

In a Laravel project, what is the difference between .env and .env.example, and which one belongs in version control?

level: juniorimportance: must knowfreq 68%
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.

open as a page

In a fresh Laravel 13 application, what belongs in app, bootstrap, config, database, public, resources, routes and storage?

level: juniorimportance: must knowfreq 60%
basics
~20 s

app 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.

open as a page

In a Laravel 13 app, what does `composer run dev` start, and why use it instead of running `php artisan serve` alone?

level: juniorimportance: must knowfreq 48%
basics
~20 s

composer 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.

open as a page

In Laravel 13, how does `laravel new` differ from `composer create-project laravel/laravel` when you start a new application?

level: juniorimportance: must knowfreq 58%
basics
~20 s

composer 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.

open as a page

In a Laravel 13 app, what do public/index.php and bootstrap/app.php each do when an HTTP request arrives?

level: juniorimportance: must knowfreq 52%
basics
~10 s

public/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().

open as a page

In Laravel, when do you need to register a service container binding, and what can auto-wiring build without one?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Laravel'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.

open as a page

In Laravel, what is the difference between using the Cache facade, the cache() helper and an injected Illuminate\Contracts\Cache\Repository?

level: juniorimportance: must knowfreq 66%
basics
~20 s

All 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.

open as a page

In a Laravel service provider, what belongs in register() and what belongs in boot(), and why does the order matter?

level: juniorimportance: must knowfreq 75%
basics
~20 s

register() 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.

open as a page

In Laravel's service container, how do bind(), singleton(), scoped() and instance() differ in what repeated resolutions return?

level: middleimportance: must knowfreq 72%
basics
~20 s

bind() 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.

open as a page

In Laravel, how does a call like Cache::get('key') reach a real object when the Cache facade class defines no static get method?

level: middleimportance: must knowfreq 72%
basics
~10 s

Cache 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.

open as a page

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?

level: juniorimportance: must knowfreq 75%
basics
~20 s

When 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.

open as a page

In Laravel, how do you name a route with ->name() and build its URL with route(), including parameters and extra query keys?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Chain ->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.

open as a page

In Laravel, how do you declare required and optional route parameters, and what must the handler supply for an optional one?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Wrap 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.

open as a page

In Laravel, which HTTP verbs do Route::get, Route::match and Route::any register, and how do you confirm them?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Route::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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~10 s

routes/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.

open as a page

In Laravel 13, what does php artisan make:controller generate, and how does a route reach one of that controller's methods?

level: juniorimportance: must knowfreq 72%
basics
~20 s

make: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.

open as a page

In Laravel, which routes does Route::resource('books', BookController::class) register, with their HTTP verbs, URIs, actions and route names?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Route::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.

open as a page

In a Laravel 13 controller, how does implementing HasMiddleware assign middleware, and how do Middleware only and except narrow it?

level: middleimportance: must knowfreq 50%
basics
~10 s

A 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.

open as a page

In Laravel, what does Route::apiResource change compared with Route::resource, and how do only() and except() narrow a resource?

level: middleimportance: must knowfreq 60%
basics
~20 s

Route::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.

open as a page

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?

level: middleimportance: should knowfreq 40%
basics
~20 s

The 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().

open as a page

In Laravel, what does php artisan make:middleware generate, and how does the generated handle() method let a request through or stop it?

level: juniorimportance: must knowfreq 74%
basics
~10 s

make: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.

open as a page

In a fresh Laravel 13 app with no config/cors.php, what answers CORS requests, and how do you change its settings?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Laravel'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.

open as a page

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?

level: juniorimportance: must knowfreq 64%
basics
~10 s

The 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.

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~10 s

Global 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.

open as a page

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?

level: middleimportance: must knowfreq 58%
basics
~10 s

Record 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.

open as a page

In Laravel, what is an API resource class such as a JsonResource, and why return one instead of the Eloquent model itself?

level: juniorimportance: must knowfreq 62%
basics
~20 s

An 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.

open as a page

In a Laravel controller, how do $request->input(), query(), all(), only() and except() differ when reading a search form?

level: juniorimportance: must knowfreq 72%
basics
~20 s

input() 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.

open as a page

In Laravel, how do redirect()->to(), redirect()->route(), to_route(), back() and redirect()->away() differ, and which status do they send?

level: juniorimportance: must knowfreq 60%
basics
~20 s

All 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Laravel'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.

open as a page

In Laravel, how do you store, read and remove session data with get(), put(), push(), pull() and forget()?

level: juniorimportance: must knowfreq 66%
basics
~20 s

Through $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.

open as a page

In a Laravel 13 Eloquent model, what does casts() declare, how does it relate to $casts, and what do common built-in casts return?

level: juniorimportance: must knowfreq 62%
basics
~20 s

casts() 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.

open as a page

In an Eloquent model, how do $hidden, $visible and $appends shape toArray() and JSON output, and what is Laravel 13's attribute form?

level: juniorimportance: must knowfreq 60%
basics
~20 s

$hidden removes attributes and relations from toArray() and JSON, $visible keeps only those listed, and $appends adds accessor values that have no column. Laravel 13 also offers #[Hidden], #[Visible] and #[Appends] class attributes; none of them changes what is queried.

open as a page

In Laravel's Eloquent, which table, primary key and timestamp columns does a model assume by convention, and how do you override them?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Eloquent 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.

open as a page

In Eloquent, what do find(), findOrFail(), first() and firstWhere() return when no matching row exists?

level: juniorimportance: must knowfreq 72%
basics
~10 s

find(), 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.

open as a page

In a Laravel blog index, how does Post::with('author') stop a Blade loop printing $post->author->name from running one query per post?

level: juniorimportance: must knowfreq 85%
basics
~20 s

Post::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.

open as a page

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?

level: juniorimportance: must knowfreq 52%
basics
~10 s

SQLite: 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.

open as a page

In a Laravel model factory, what is the difference between make() and create(), and what does each return?

level: juniorimportance: must knowfreq 62%
basics
~20 s

make() 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.

open as a page

In Laravel, how do you organise and run database seeders, and what do db:seed --class and migrate --seed do?

level: juniorimportance: must knowfreq 58%
basics
~20 s

A 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.

open as a page

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?

level: juniorimportance: must knowfreq 72%
basics
~20 s

It 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.

open as a page

In Laravel, what is the difference between paginate(), simplePaginate() and cursorPaginate(), and which SQL queries does each run?

level: juniorimportance: must knowfreq 60%
basics
~20 s

paginate() 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.

open as a page

In Laravel, how do Cache::lock()'s get() and block() differ when two queue workers try to generate the same monthly statement at once?

level: juniorimportance: must knowfreq 48%
basics
~10 s

Cache::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.

open as a page

In Laravel, how does Cache::remember() cache an expensive exchange-rate lookup, and what happens on a cache hit versus a miss?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Cache::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.

open as a page

In Laravel 13, which cache store does a fresh app use, how does CACHE_STORE select it, and how does the failover store behave?

level: juniorimportance: should knowfreq 55%
basics
~20 s

A 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.

open as a page

In Laravel 13, which cache stores can back Cache::lock() across servers, and where do the database and Redis stores keep their locks?

level: middleimportance: should knowfreq 30%
basics
~20 s

Cross-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.

open as a page

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()?

level: middleimportance: should knowfreq 30%
basics
~10 s

Acquire 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.

open as a page

In Laravel Blade, what is the difference between a class-based component and an anonymous component, and when would you choose each?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Blade 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.

open as a page

In a Blade view, what is the difference between {{ $value }} and {!! $value !!}, and when is the raw form acceptable?

level: juniorimportance: must knowfreq 82%
basics
~20 s

Blade 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.

open as a page

In Laravel Blade, how does a layout component with {{ $slot }} differ from an @extends layout, and which suits a new app?

level: juniorimportance: must knowfreq 68%
basics
~20 s

A 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.

open as a page

In a Blade component, how does $attributes->merge() treat class compared with other attributes, and when do you need class() or prepends()?

level: middleimportance: must knowfreq 55%
basics
~20 s

merge() 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.

open as a page

Which official starter kits does Laravel 13 offer, and what does each one give a brand-new application?

level: juniorimportance: must knowfreq 52%
basics
~20 s

Laravel 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.

open as a page

In a Laravel Blade layout, what does the @vite directive output, and how does that differ between npm run dev and npm run build?

level: juniorimportance: must knowfreq 62%
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.

open as a page

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?

level: middleimportance: must knowfreq 42%
basics
~20 s

A 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.

open as a page

In Laravel, how do Blade, Livewire, Inertia and a separate SPA on a JSON API differ in routing ownership and where UI state lives?

level: middleimportance: must knowfreq 50%
basics
~20 s

Blade, 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).

open as a page

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?

level: middleimportance: must knowfreq 46%
basics
~20 s

Laravel'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.

open as a page

In Laravel, how do `php artisan list`, `php artisan help` and `php artisan about` help you get oriented in an unfamiliar application?

level: juniorimportance: must knowfreq 55%
basics
~10 s

php 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.

open as a page

In Laravel, what do the `make:*` Artisan generators do, and what does `php artisan make:model Shipment -a` create?

level: juniorimportance: must knowfreq 65%
basics
~10 s

make:* 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.

open as a page

In Laravel 13, how do you create a custom Artisan command with `make:command`, and how are its signature, description and `handle()` wired up?

level: juniorimportance: must knowfreq 65%
basics
~10 s

php 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.

open as a page

What is Laravel Pint, and how do you run it to fix the code style of a Laravel application?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Laravel 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.

open as a page

What is Laravel Sail, and how do you add it to a Laravel 13 application and start its containers?

level: juniorimportance: must knowfreq 50%
basics
~20 s

Laravel 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.

open as a page

In a Laravel 13 controller, what does $request->validate() return on success, and what happens when validation fails?

level: juniorimportance: must knowfreq 78%
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.

open as a page

In a Laravel Blade view, how do you show validation errors after a failed form submission, and where does the $errors variable come from?

level: juniorimportance: must knowfreq 76%
basics
~20 s

A 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().

open as a page

In Laravel, what is a form request class, and when does it authorize and validate the request relative to your controller method?

level: middleimportance: must knowfreq 75%
basics
~20 s

A 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.

open as a page

In Laravel, when would you use Validator::make() instead of $request->validate(), and how do fails(), validate() and validated() differ?

level: middleimportance: must knowfreq 62%
basics
~20 s

Validator::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.

open as a page

In Laravel, where can you override a validation error message or the :attribute name, and in what order does the validator look for them?

level: middleimportance: must knowfreq 62%
basics
~20 s

Pass 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.

open as a page

In a Laravel 13 Blade form, what does @csrf add, and when does a POST without a valid token fail with a 419 error?

level: juniorimportance: must knowfreq 78%
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.

open as a page

In Laravel, what is APP_KEY, what does php artisan key:generate write, and what happens when the key is missing?

level: juniorimportance: must knowfreq 66%
basics
~20 s

APP_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.

open as a page

In Laravel, how do Hash::make() and Hash::check() store and verify a password, and why is Crypt::encryptString() the wrong tool for it?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Hash::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.

open as a page

A payment provider's webhook POST to your Laravel 13 app gets 419 responses; why, and how do you exempt that route correctly?

level: middleimportance: must knowfreq 55%
basics
~20 s

Routes 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.

open as a page

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?

level: seniorimportance: must knowfreq 45%
basics
~20 s

Set 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.

open as a page

In Laravel, what is the difference between a gate defined with Gate::define and a policy class, and when would you choose each?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A 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.

open as a page

In Laravel's config/auth.php, what is the difference between a guard and a user provider, and what ships by default?

level: juniorimportance: must knowfreq 55%
basics
~20 s

A 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).

open as a page

In Laravel, how does a hand-built login use Auth::attempt, and why does the documented example call $request->session()->regenerate() afterwards?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Auth::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().

open as a page

In Laravel, what must be in place for the verified middleware to keep users with unconfirmed email addresses out of a route?

level: juniorimportance: must knowfreq 50%
basics
~10 s

App\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'].

open as a page

What two authentication mechanisms does Laravel Sanctum provide, and which one suits a first-party SPA versus a mobile app?

level: juniorimportance: must knowfreq 68%
basics
~20 s

Sanctum 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.

open as a page

Why must APP_DEBUG be false on a production Laravel app, and what does the debug exception page reveal when it is true?

level: juniorimportance: must knowfreq 62%
basics
~20 s

With 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.

open as a page

In Laravel, what is the difference between the dump() and dd() helpers, and when is Log::debug() the better choice?

level: juniorimportance: must knowfreq 66%
basics
~20 s

dump() 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Create 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.

open as a page

In Laravel, what does the report() helper do, and when would you call it instead of letting an exception propagate?

level: juniorimportance: must knowfreq 50%
basics
~20 s

report($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.

open as a page

In a Laravel 13 app, what do LOG_CHANNEL, LOG_STACK and LOG_LEVEL control, and where do log entries go by default?

level: juniorimportance: must knowfreq 60%
basics
~10 s

LOG_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.

open as a page

In Laravel 13, where is the application's default locale configured, and how do you switch the locale for the current request?

level: juniorimportance: must knowfreq 55%
basics
~10 s

The 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Create 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.

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~10 s

Write 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.

open as a page

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?

level: middleimportance: must knowfreq 48%
basics
~20 s

Use 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.

open as a page

In a Laravel translation string, how are :name, :Name and :NAME placeholders filled, and what happens to a placeholder you do not pass?

level: juniorimportance: should knowfreq 38%
basics
~20 s

Pass 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.

open as a page

In Laravel, what is the difference between Bus::chain and Bus::batch, and when would you use each for queued jobs?

level: juniorimportance: must knowfreq 45%
basics
~20 s

Bus::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.

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Run 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().

open as a page

In Laravel, which Artisan commands list, retry and delete failed queued jobs, and what does queue:retry actually do with a failed job?

level: juniorimportance: must knowfreq 56%
basics
~10 s

php 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.

open as a page

In Laravel, what is the difference between php artisan queue:work and php artisan queue:listen, and which belongs in production?

level: juniorimportance: must knowfreq 62%
basics
~20 s

queue: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.

open as a page

In Laravel, why can a job dispatched inside DB::transaction during sign-up fail on the worker, and how does afterCommit fix it?

level: middleimportance: must knowfreq 58%
basics
~20 s

The 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.

open as a page

In Laravel 13, where do you define scheduled tasks, and how does a single cron entry running schedule:run execute all of them?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Tasks 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.

open as a page

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?

level: middleimportance: must knowfreq 52%
basics
~20 s

Schedule::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.

open as a page

In Laravel's scheduler, what does withoutOverlapping() do, where is its lock stored, and how long does that lock last by default?

level: middleimportance: must knowfreq 55%
basics
~20 s

withoutOverlapping() 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.

open as a page

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?

level: seniorimportance: must knowfreq 48%
basics
~20 s

Each 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.

open as a page

In Laravel's scheduler, do tasks due in the same minute run in parallel, and what changes when you add runInBackground() to one?

level: juniorimportance: should knowfreq 40%
basics
~10 s

No: 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.

open as a page

In Laravel 13, what steps does it take to broadcast a server-side event such as BidPlaced so that browsers receive it through Echo?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Run 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.

open as a page

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?

level: juniorimportance: must knowfreq 68%
basics
~10 s

Run 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.

open as a page

In Laravel, what do a mailable's envelope(), content() and attachments() methods define, and how do you send that mailable to a customer?

level: juniorimportance: must knowfreq 62%
basics
~10 s

A 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.

open as a page

In Laravel, what does a notification class contain, how does its via() method pick delivery channels, and how do you send it?

level: juniorimportance: must knowfreq 58%
basics
~20 s

A 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, ...).

open as a page

What is Laravel Reverb, how does it sit between a Laravel app and Echo, and why does it speak the Pusher protocol?

level: juniorimportance: must knowfreq 38%
basics
~20 s

Reverb 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.

open as a page

In Laravel, what do Storage::put(), get(), exists() and delete() return on success and failure, and what does a disk's throw option change?

level: juniorimportance: must knowfreq 56%
basics
~20 s

put(), 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.

open as a page

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?

level: middleimportance: must knowfreq 60%
basics
~20 s

Storage 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.

open as a page

In Laravel, when do you use Storage::url() versus Storage::temporaryUrl(), for example for private medical documents that should download for ten minutes?

level: middleimportance: must knowfreq 62%
basics
~10 s

Storage::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.

open as a page

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?

level: middleimportance: should knowfreq 38%
basics
~20 s

AWS_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.

open as a page

In Laravel, what does the RefreshDatabase trait do to the test database, and why is it the usual default for feature tests?

level: juniorimportance: must knowfreq 72%
basics
~20 s

RefreshDatabase 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.

open as a page

In a Laravel feature test, how do you request a sneaker shop's checkout routes and assert the status, redirect and view data?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Call $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.

open as a page

In a Laravel 13 app, how do tests in tests/Feature differ from tests in tests/Unit, and which base class does each extend?

level: juniorimportance: must knowfreq 68%
basics
~10 s

Feature 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.

open as a page

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?

level: middleimportance: must knowfreq 64%
basics
~10 s

Call 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.

open as a page

In a Laravel feature test, what does actingAs($user) do, and how does it differ from logging in through the login route?

level: middleimportance: must knowfreq 60%
basics
~20 s

actingAs($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.

open as a page

In Laravel, what does collect() return, and does chaining map() and filter() on it change the original collection?

level: juniorimportance: must knowfreq 72%
basics
~10 s

collect() 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

No. 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.

open as a page

In Laravel, what is the difference between a Collection and a LazyCollection, and when would you reach for the lazy one?

level: juniorimportance: must knowfreq 42%
basics
~20 s

A 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.

open as a page

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?

level: juniorimportance: must knowfreq 42%
basics
~10 s

Process::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.

open as a page

In Laravel, what do now() and today() return, and how do you show an order's age as '3 days ago' with Carbon?

level: juniorimportance: must knowfreq 50%
basics
~10 s

now() 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'.

open as a page

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?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Fetch 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.

open as a page

In the Laravel ecosystem, how do Laravel Cloud, Laravel Forge and Laravel Vapor differ in who runs the servers your app lives on?

level: juniorimportance: must knowfreq 50%
basics
~20 s

Laravel 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

php 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.

open as a page

In Laravel 13, what does php artisan optimize cache, and what does php artisan optimize:clear remove?

level: juniorimportance: must knowfreq 62%
basics
~10 s

php 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.

open as a page

After installing Laravel Pulse, why does the /pulse dashboard return 403 in production, and how do you grant access to it?

level: juniorimportance: must knowfreq 30%
basics
~20 s

Pulse 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.

open as a page

What is Laravel Cashier (Stripe) for, and what does adding the Billable trait to the User model give you?

level: juniorimportance: must knowfreq 38%
basics
~20 s

Laravel 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.

open as a page

In Laravel Pennant, how do you define a feature with Feature::define(), check it with Feature::active(), and what scope is used by default?

level: juniorimportance: must knowfreq 30%
basics
~10 s

Feature::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.

open as a page

In Laravel Scout, what does adding the Searchable trait to an Eloquent model do, and how does its search index stay in sync?

level: juniorimportance: must knowfreq 42%
basics
~20 s

The 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.

open as a page

In Laravel Cashier, how does newSubscription(...)->checkout() start a subscription, and when does the local subscriptions row appear?

level: middleimportance: should knowfreq 30%
basics
~20 s

newSubscription('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.

open as a page

In Laravel Cashier, how do swap(), cancel(), cancelNow() and resume() change a subscription, and what do onTrial() and onGracePeriod() report?

level: middleimportance: should knowfreq 32%
basics
~20 s

swap() 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.

open as a page