PHP and Laravel¶
Scope: web applications and APIs built with Laravel and PHP, with Eloquent, Blade, queues and Horizon. On 2026-11-01, Laravel 13 is the current release: it needs PHP 8.3 or later, gets bug fixes until the third quarter of 2027 and security fixes until 17 March 2028. Laravel 12 gets security fixes only, until 24 February 2027. For configuration, health checks, telemetry and resilience, follow general/operations-reliability.md; for secrets, authorization and the supply chain, general/security.md; for sign-in and sessions, general/authentication.md; for migrations and idempotent message handling, general/data.md. Browser-side rules for accessibility, performance and security are in Web front end; databases, caches and containers have their own folders, such as PostgreSQL, Redis and caching and Docker. The rules here cover what is specific to Laravel.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 Laravel documentation (Laravel): the baseline. Configuration, routing, requests and validation, Blade, authentication and authorization, CSRF protection, Eloquent and migrations, queues, file storage, testing and deployment.
- 8 Deployment (Laravel docs): server requirements, a web server configuration, the caches to build during deployment, debug mode, the health route, and reloading long-running processes.
- 7 Release notes: support policy and upgrade guide (Laravel docs): the bug-fix and security-fix dates and PHP versions of each Laravel release, and the breaking changes to handle when you move to the next one.
- 7 Supported Versions (PHP): the active-support and security-support end dates of each PHP branch.
- 6 Laravel Cheat Sheet (OWASP): Laravel security settings and pitfalls, such as cookies and sessions, mass assignment, SQL injection, XSS, file uploads, CSRF and rate limiting.
- 6 Horizon (Laravel docs): a dashboard and code-driven worker configuration for queues that run on Redis, with metrics, tags and failed-job management. Use it when your queues run on Redis.
- 6 PER Coding Style (PHP-FIG): the PHP coding style that extends and replaces PSR-12.
Key rules¶
Configuration and deployment¶
- 9
LARAVEL-1Never commit the.envfile: commit.env.examplewith placeholder values, and supply the real values as environment variables on the server or in an encrypted environment file (php artisan env:encrypt). GenerateAPP_KEYwithphp artisan key:generate; when you rotate it, list the old keys inAPP_PREVIOUS_KEYS, so that existing sessions and encrypted data keep working. This is how Laravel applications followSEC-2in general/security.md. (Laravel, Environment file security, Encrypting environment files, Encryption: configuration, Gracefully rotating encryption keys) - 9
LARAVEL-2In production, setAPP_DEBUGtofalseand point the web server's document root at thepublicdirectory. With debug mode on, error pages can expose sensitive configuration values to users, and serving the project root exposes sensitive configuration files to the internet. (Laravel, Deployment: debug mode, Deployment: Nginx) - 7
LARAVEL-3Runphp artisan optimizein every deployment, to cache the configuration, events, routes and views; callenv()only in the files inconfig/; and restart queue workers and other long-running processes after deploying, for example withphp artisan reload. Once the configuration is cached, Laravel no longer loads.env, soenv()calls elsewhere returnnullfor values that are defined only in.env. (Laravel, Deployment: optimization, Configuration caching, Deployment: reloading services)
Security¶
- 9
LARAVEL-4Authorize every action: write the rules for each model in a policy and the other rules in gates, and check them in each controller action, in the Form Request'sauthorize()method, or with thecanmiddleware. Gates and policies deny guests by default. This is how Laravel applications applySEC-1in general/security.md. (Laravel, Authorization, Authorizing actions via middleware, Guest users, Authorizing form requests) - 9
LARAVEL-5Output data with Blade's escaped{{ }}syntax, use{!! !!}only for HTML you trust, never for content that users supplied, and pass data to JavaScript withJs::from().{{ }}runs values throughhtmlspecialcharsto prevent XSS. This is how Blade templates applyWEB-8; for sanitizing HTML and Content Security Policy, see Web front end. (Laravel, Blade: displaying unescaped data, Rendering JSON) - 9
LARAVEL-6Pass values to raw SQL only as bindings, with?or named placeholders, inDB::select(),whereRaw(),orderByRaw()and the other raw methods, and never let user input choose column names, includingorderBycolumns. The query builder binds values for you, but raw expressions are inserted into the query as strings, PDO can't bind column names, andDB::unprepared()binds nothing. This appliesSEC-18. (Laravel, Query builder, Raw methods, Database: running a select query, Running an unprepared statement) - 8
LARAVEL-7Validate every request with a Form Request or the validator, pass only the validated data ($request->validated()orsafe()) tocreate(),fill()andupdate(), and declare each model's mass-assignable attributes with theFillableattribute (the$fillableproperty before Laravel 13) instead of unguarding the model. Otherwise a user can send an extra field, such asis_admin, that changes a column you didn't expect. In development,Model::preventSilentlyDiscardingAttributes()throws when code fills an attribute that isn't fillable. This appliesSEC-10in general/security.md. (Laravel, Form request validation, Working with validated input, Eloquent: mass assignment, Allowing mass assignment, Mass assignment exceptions) - 7
LARAVEL-8Validate the type and size of every upload with theFilerule, for exampleFile::types([...])->max('10mb')orFile::image(), and store it under a generated name withstore()orhashName(), never a name built fromgetClientOriginalName(),getClientOriginalExtension()or other user input. An attacker could upload a file namedshell.phpand run it if the storage is web-accessible.File::types()checks the file's content, not only its extension, and the image rule rejects SVG files unless you allow them. (Laravel, Validating files, Validating file types, File storage: file uploads, Specifying a file name, Other uploaded file information) - 7
LARAVEL-9Keep browser routes in thewebmiddleware group, where thePreventRequestForgerymiddleware checks them, add@csrfto everyPOST,PUT,PATCHandDELETEform, and exclude only routes that can't send a token, such as third-party webhooks, from CSRF protection. For a single-page app that uses Laravel as its API, follow the Sanctum documentation. This appliesAUTH-17. (Laravel, Preventing CSRF requests, Excluding URIs from CSRF protection)
Database¶
- 8
LARAVEL-10Change the schema only through migrations indatabase/migrations, run them in each deployment withphp artisan migrate --force, and add--isolatedwhen several servers deploy at once.--isolatedtakes a lock, so that only one server runs the migrations. This is how Laravel applications followDATA-2in general/data.md. (Laravel, Migrations, Isolating migration execution, Forcing migrations to run in production) - 7
LARAVEL-11Eager load the relationships that each query's results use withwith()orload(), and callModel::preventLazyLoading(! $this->app->isProduction())inAppServiceProvider, so that lazy loading throws an exception in development and tests. Production keeps working if a lazy load slips through. This is how Eloquent appliesDATA-10. (Laravel, Eager loading, Preventing lazy loading) - 7
LARAVEL-12Wrap writes that must succeed or fail together inDB::transaction(), passattemptsto retry on deadlocks, and dispatch queued jobs from inside a transaction only after it commits, with the queue connection'safter_commitoption or->afterCommit(). Otherwise a worker can pick up the job before the transaction commits, when the records it needs may not exist yet. (Laravel, Database transactions, Handling deadlocks, Queues: jobs and database transactions)
Queues¶
- 7
LARAVEL-13Run slow work, such as processing uploaded files, in queued jobs; make each job safe to run more than once, keep each worker's--timeoutseveral seconds shorter than the connection'sretry_after, limit the attempts, and keep failed jobs in thefailed_jobstable to inspect and retry them. If--timeoutis longer thanretry_after, a job can be processed twice. Idempotent consumers areDATA-9in general/data.md. (Laravel, Queues, Job expirations and timeouts, Dealing with failed jobs)
Code quality and testing¶
- 6
LARAVEL-14Write most tests as feature tests that send HTTP requests to the application and assert on the response and the database, reset the database for each test withRefreshDatabase, and create test data with model factories. The Laravel docs say most tests should be feature tests. Their requests are simulated inside the test process, without a real network request; Laravel supports both Pest and PHPUnit. (Laravel, Testing, HTTP tests: making requests, Database testing: resetting the database, Model factories) - 6
LARAVEL-15Check the code style with Laravel Pint, and analyse the code with Larastan, the PHPStan extension for Laravel, in CI. Pint uses itslaravelpreset by default; choose theperorpsr12preset to follow the PHP-FIG style. (Laravel, Pint, Pint presets, Larastan)
Versions¶
- 8
LARAVEL-16Run a Laravel release that still receives security fixes, on a PHP branch that is still supported, and plan each upgrade before the support ends. Laravel releases get bug fixes for 18 months and security fixes for 2 years, and PHP branches get 2 years of active support and 2 more of security fixes; for example, PHP 8.2 reaches end of life on 31 December 2026. Commitcomposer.lock, and runcomposer auditin CI. This is how Laravel applications followSEC-17in general/security.md. (Laravel, Support policy, Upgrade guide, PHP, Supported Versions, Composer, Commit your composer.lock file, Composer, audit)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 GitHub secret scanning push protection: blocks pushes that contain credentials, for example a committed
.envfile. See general/security.md for more secret scanners. Partly checksLARAVEL-1. - 6 Larastan rules:
NoEnvCallsOutsideOfConfig, on by default, reportsenv()calls outside the config directory, andJobDispatchedInTransactionUsesAfterCommitRule, turned on withcheckDispatchInTransactionAfterCommit, reports jobs dispatched insideDB::transaction()withoutafterCommit(). Partly checksLARAVEL-3,LARAVEL-12andLARAVEL-15. - 6 Psalm Laravel plugin, security analysis: taint analysis that follows request input to sinks such as
orderBy()columns,orderByRaw(),DB::select()andDB::unprepared(), to file storage paths, and, when turned on, to{!! !!}in Blade templates. Partly checksLARAVEL-5,LARAVEL-6andLARAVEL-8. - 6 Laravel Pint
--test: fails with a non-zero exit code when files don't match the configured style. Partly checksLARAVEL-15. - 6
composer audit: exits with an error when an installed package, such aslaravel/framework, has a security advisory, or is abandoned or flagged as malware. Partly checksLARAVEL-16. - 5 Semgrep Laravel rules:
laravel-blade-form-missing-csrfflags state-changing forms without@csrf,laravel-dangerous-model-constructionflags$guarded = [], andlaravel-active-debug-codeflags code that setsAPP_DEBUGto true. Partly checksLARAVEL-2,LARAVEL-7andLARAVEL-9.
Tutorials and further reading¶
- 7 Getting Started with Laravel (Laravel): the official course that builds a first full-stack application from start to finish.
- 6 Laravel From Scratch, 2026 edition (Laracasts): a free introductory video series, refreshed every two years and covering Laravel 12 and later, from the fundamentals to authentication, authorization, queues, testing and deployment.
- 5 PHP The Right Way (community): current PHP practices, coding standards, dependency management, security and testing, for any PHP project.