PHP and Laravel
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
This section is about building web applications with PHP. It starts with what plain PHP gives you: how a request reaches a script, how to read input, escape output, keep sessions, accept uploads, query a database with PDO and avoid the common security mistakes. It then builds the same kind of application with Laravel, the most widely used PHP framework, from a first route to production. It is written for developers who know some PHP, or another web framework, and want to build and run current PHP web applications. The language itself (syntax, types, objects, the standard library, Composer and testing tools) is covered in the PHP Reference, which these pages link to rather than repeat.
The pages are written against Laravel 13.x (13.34.0) on PHP 8.3 to 8.5, checked on 2026-10-05. Laravel ships one major version a year, and each one gets bug fixes for 18 months and security fixes for two years. Laravel 13 was released on 2026-03-17 and requires PHP 8.3 or newer. On 2026-10-05, Laravel 12 receives security fixes only, and 11 and older receive none. Laravel 14 is expected in the first quarter of 2027. PHP itself supports each release for four years, and 8.3 is in security-only support until the end of 2027. The details are on What’s Changed and Upgrading.
The two running examples
The examples on these pages build two small, original applications in the same domain as the Django, FastAPI and NestJS sections of this site, so that the stacks can be compared:
-
Bookshelf Lite is a book catalogue in plain PHP with PDO, a front controller and no framework. The plain PHP pages build it so that you can see exactly what a framework takes over.
-
Bookshelf is the same catalogue in Laravel 13: books, authors, reviews and loans with Blade pages, search and pagination, a starter-kit login with policies for editing reviews, cover uploads to an S3-compatible disk, English and Spanish translations, a live feed of new reviews over Reverb (and a server-sent events variant), moderation mail and notifications on a queue, Redis caching, a versioned JSON API with Sanctum and a JSON:API variant, scheduled tasks, and a Docker and FrankenPHP deployment.
Every Laravel example was run in that application, and its test suite (109 Pest tests at the end of this section) covers the examples that have behaviour to check. The pages say where something could not be run in the environment used to write them.
New here? Read in this order
-
Introduction and Architecture — how PHP serves the web, MVC and where Laravel stands among the frameworks.
-
The PHP Request Model and Servers, then the plain PHP pages up to Web Security Fundamentals. Readers who already know PHP on the web can skip to the next step.
-
Laravel Getting Started and the rest of Laravel foundations, in order.
-
The HTTP layer, from Routing to Validation and Form Requests, and Blade Templates.
-
Authentication, Authorization: Gates and Policies and Testing.
-
Queues and Jobs and Deployment, before the first release.
The other pages can be read as needed. Coming from an older book, tutorial or Laravel version? Start with What’s Changed and Upgrading. Every page ends with a section on where older material is outdated, and Best Practices collects the rules in one checklist.
What’s covered
Foundations
-
Introduction and Architecture — how PHP serves the web, MVC and the front controller, framework or library, Active Record and Data Mapper, the Symfony components Laravel is built from, Laravel among PHP frameworks and other stacks, and where WordPress and Drupal fit.
Web development in plain PHP
-
The PHP Request Model and Servers — the shared-nothing model, SAPIs, PHP-FPM behind Nginx, FrankenPHP and worker mode, OPcache and persistent connections.
-
HTTP Requests and Responses — superglobals, JSON, PUT and PATCH bodies, status codes and headers, output buffering, URL parsing with the URI extension, and PSR-7.
-
Forms, Validation and Output Escaping — Post/Redirect/Get, validating input, escaping for each context, why "sanitize on input" is wrong, and mail header injection.
-
Sessions and Cookies — how sessions work, the security settings, fixation and hijacking, locking, storage, flash messages, cookies and logging out.
-
File Uploads and Images — the upload settings,
$_FILES, validating and storing uploads, serving downloads, and resizing with GD. -
Databases with PDO — connecting, prepared statements and SQL injection, fetch modes, transactions, a repository, and mysqli.
-
Authentication Without a Framework — registration and login, throttling, "remember me", password reset and HTTP Basic authentication.
-
Web Security Fundamentals — the PHP Manual’s security chapter, the OWASP Top 10:2025 for PHP, CSRF, injection, SSRF, deserialization, misconfiguration, secrets, headers and patching.
-
Templating, Routing and Middleware by Hand — PHP as a template language, a front controller and router, PSR-7, PSR-15 and PSR-11, the same application in Slim 4, and why a full framework pays off.
-
HTTP Clients, APIs and Email — a small JSON API, cURL, stream contexts, PSR-18 clients and sending email.
Laravel foundations
-
Laravel Getting Started — installing PHP, Composer and the installer, creating and running an application, the first route-controller-model-view loop, and releases.
-
Directory Structure and Configuration — the slim skeleton,
bootstrap/app.php,.envandconfig(), environments, debug and maintenance mode. -
Request Lifecycle — from
index.phpthrough providers, middleware and routing to the response, and what changes under Octane. -
Service Container, Providers and Facades — autowiring, bindings and lifetimes, contextual binding, providers, facades and contracts.
-
Artisan, Tinker and Prompts — the built-in commands, writing commands, Tinker, Laravel Prompts and testing commands.
HTTP layer
-
Routing — route files, parameters, model binding, groups, rate limiting, signed URLs, route caching and Folio.
-
Middleware — writing and registering middleware, the default groups, parameters and priority, terminable middleware, the
#[Middleware]attribute and trusted proxies. -
Controllers — basic, single-action and resource controllers, middleware and authorization attributes, injection, and thin controllers with action classes.
-
Requests, Input and Responses — input, files and cookies, every response type, redirects, downloads and streamed responses.
-
Validation and Form Requests — rules, errors and old input, Form Requests, rule objects, custom rules and Precognition.
-
Sessions, Cookies and Flash Data — drivers, flash data, regeneration, JSON serialization in Laravel 13, session blocking and cookies.
-
Error Handling and Logging — exceptions in
bootstrap/app.php, error pages, debug output, log channels, context and Pail.
Views and the front end
-
Blade Templates — layouts, escaping and XSS, JSON for JavaScript, directives, fragments, view composers and page metadata.
-
Blade Components and Layouts — class and anonymous components, attributes and slots, layouts and component packages.
-
Vite and Frontend Assets —
@vite, static assets, JavaScript frameworks, CSP nonces, choosing a front end and migrating from Mix. -
Livewire — Livewire 4 components,
wire:model, actions, forms, events, lazy loading, testing, Flux and Alpine.js. -
Inertia and Starter Kits — Inertia 3 with React, props and shared data, forms and errors, SSR, testing, and the starter kits.
Database and Eloquent
-
Database and Query Builder — connections, raw queries and bindings, the query builder, upserts, transactions and locking, and chunking.
-
Migrations, Seeders and Factories — schema changes, running and squashing migrations, seeders and factories.
-
Eloquent Models — conventions, Laravel 13 model attributes, mass assignment, events and observers, scopes, soft deletes and strict mode.
-
Eloquent Relationships — every relationship type, syncing, reading and eager loading.
-
Eloquent Casts, Accessors and Serialization —
casts(), JSON columns, enum and value-object casts, accessors and serialization. -
Collections and Pagination — collections, lazy collections, string and array helpers,
once(), pipelines and pagination. -
Query Performance and N+1 — the N+1 problem, query plans and indexes, eager loading strategies, lazy-loading prevention and finding slow queries.
-
Redis, MongoDB and Search — Redis, MongoDB with Eloquent, full-text and vector search, and Scout.
Security
-
Authentication — guards and providers, logging in by hand, e-mail verification, password reset, Fortify with two-factor and passkeys, and Socialite.
-
Authorization: Gates and Policies — roles, gates, policies and checking abilities everywhere.
-
API Authentication: Sanctum and Passport — choosing between them, API tokens, SPA authentication and an OAuth 2 server.
-
Security: CSRF, Encryption and Hashing —
PreventRequestForgery, encryption and key rotation, password hashing, CORS, CSP and secrets.
APIs and integrations
-
Building APIs and API Resources — API resources, JSON:API resources, versioning, documentation and testing.
-
HTTP Client — requests, timeouts, retries, configured clients, concurrency and
Http::fake(). -
AI SDK, MCP and Boost — the Laravel AI SDK, MCP servers and Laravel Boost.
Application services
-
Queues and Jobs — drivers, job classes and attributes, workers, failures, transactions, unique jobs, chains and batches, Horizon and idempotency.
-
Events and Listeners — events, discovery, transactions, model and domain events, and when not to use one.
-
Broadcasting and Reverb — broadcast events, channel authorization, the protocol, Echo, Reverb in production and server-sent events.
-
Task Scheduling — the cron entry, schedules, overlaps and several servers, and testing.
-
Mail and Notifications — mailers, Mailables, queued and translated mail, previews, failover and notifications.
-
Cache and Rate Limiting — stores,
rememberandflexible, tags, atomic locks, failover and rate limiting. -
File Storage and Images — disks, public and private files, S3, temporary URLs, images and testing.
-
Localization — translation files, choosing the locale and what Laravel does not translate.
-
Processes, Concurrency and Context — running processes, the
Concurrencyfacade,Contextand feature flags with Pennant.
Testing
-
Testing — the testing environment, Pest, parallel runs and coverage, HTTP and console tests, the database and the fakes.
-
Browser Testing with Dusk — Dusk and ChromeDriver, page objects, the Pest browser plugin and CI.
Production and evolution
-
Deployment — Nginx and PHP-FPM,
optimizeand OPcache, releases, long-running processes, FrankenPHP and managed platforms. -
Docker and Sail — Sail for development, a production image, and web, worker and scheduler containers from one image.
-
Octane and Performance — Octane on FrankenPHP, what it gains, state leaks between requests, OPcache and measuring.
-
Monitoring and Debugging — Telescope, Pulse, Nightwatch, Pail, the exception page and Xdebug.
-
Package Development and Ecosystem — writing and testing a package, and the first-party and community ecosystem.
-
What’s Changed and Upgrading — releases 6 to 13, the support policy, old code on Laravel 13, the slim skeleton, upgrading and what older books get wrong.
-
Best Practices — the practices that still hold, in one checklist.
-
Cheat Sheet — a one-page summary of the section, with a downloadable PDF.
Where related material lives elsewhere on this site
These pages link to existing material instead of repeating it, and cover only the PHP and Laravel side.
| Topic | Where it lives | How this section relates |
|---|---|---|
The PHP language, Composer, static analysis and PHPUnit/Pest |
Pages link there for syntax, types, objects, the standard library and tooling. |
|
HTML, CSS, JavaScript and TypeScript |
HTML & CSS Reference, JavaScript Development and TypeScript Reference |
The Blade, Vite, Livewire and Inertia pages cover only the Laravel side. |
Front-end frameworks and Tailwind CSS |
Inertia pages and the starter kits use React, Vue and Tailwind as they are documented there. |
|
Accessibility, CORS and browser testing |
Web Accessibility, What is CORS? and E2E Testing in Real Browsers |
The security and Dusk pages show Laravel’s configuration and APIs. |
The same ideas in other stacks |
Django, ASP.NET Reference, Vaadin Reference, Python FastAPI, NestJS, SpringBoot Reference and Quarkus Reference |
Introduction and Architecture compares them. |
OAuth 2.0, OpenID Connect, PKCE and multi-factor authentication |
The authentication and Sanctum/Passport pages cover only the Laravel packages. |
|
Messaging, scheduling and resilience patterns |
The queues, scheduling, HTTP client and rate-limiting pages show the Laravel parts. |
|
Containers, Kubernetes and cloud platforms |
Docker, Kubernetes and Cloud |
The Docker, Sail and deployment pages cover only what PHP and Laravel need. |
SQL, query tuning, pagination and schema changes |
SQL Reference, Diagnosing and Fixing Slow Queries, Pagination: Offset vs. Keyset and Evolving the Database Model |
The PDO, query builder, migrations, N+1 and pagination pages cover the PHP side. |
Redis, MongoDB, Elasticsearch and vector search |
Redis Reference, MongoDB Reference, Elasticsearch Reference and Vector Databases & RAG |
The cache and Redis, MongoDB and search pages show only the Laravel clients. |
GraphQL |
The API page mentions Lighthouse for GraphQL in Laravel. |
|
MCP, agents and AI-assisted development |
Model Context Protocol (MCP), AI Agents, AI-Assisted Development and RAG Systems in Production |
The AI SDK, MCP and Boost page covers only the Laravel APIs. |
The open issues for a comparison of backend and web frameworks (#263), of programming languages (#196) and of cloud providers (#201), and a future Symfony section, will add pages that this section will link to once they exist.
Bibliography
The reference material consulted while preparing this section. The PHP Manual, the Laravel documentation and the official documentation of each tool are the primary sources; the books are consulted references, not the primary source. On any discrepancy, or wherever a book is silent on a later feature, the official documentation wins. No text, code listing or figure is copied from any book.
Books
-
Andrew Beak, PHP 7 Zend Certification Study Guide: Ace the ZCE 2017-PHP Exam, 1st edition, Apress, 2017. ISBN 978-1-4842-3245-3 (print), 978-1-4842-3246-0 (eBook), DOI 10.1007/978-1-4842-3246-0. Targets PHP 7.1; its security, web-features and database chapters were consulted.
-
David Powers, PHP 7 Solutions: Dynamic Web Design Made Easy, 4th edition, Apress, 2019. ISBN 978-1-4842-4337-4 (print), 978-1-4842-4338-1 (eBook), DOI 10.1007/978-1-4842-4338-1. Targets PHP 7.2/7.3 with MySQL or MariaDB. Companion code: Apress/php-7-solutions. Current edition: PHP 8 Solutions, 5th edition (ISBN 978-1-4842-7140-7), companion code Apress/php-8-solutions.
-
Frank M. Kromann, Beginning PHP and MySQL: From Novice to Professional, 5th edition, Apress, 2018. ISBN 978-1-4302-6043-1 (print), 978-1-4302-6044-8 (eBook), DOI 10.1007/978-1-4302-6044-8. Targets PHP 7.0-7.2 with MySQL 5.x or MariaDB. Companion code: Apress/beginning-php-and-mysql-5e.
-
Bartosz Porębski, Karol Przystalski and Leszek Nowak, Building PHP Applications with Symfony, CakePHP, and Zend Framework, Wiley (Wrox), 2011. ISBN 978-0-470-88734-9. Targets PHP 5.2/5.3, Symfony 1.4, CakePHP 1.3 and Zend Framework 1.10/1.11; consulted for framework concepts and comparisons.
-
Matt Stauffer, Laravel: Up & Running — A Framework for Building Modern PHP Apps, 2nd edition, O’Reilly Media, 2019. ISBN 978-1-492-04121-4. Targets Laravel 5.8 on PHP 7.1.3. Current edition: the 3rd edition (2023, Laravel 10).
-
Robin Nixon, Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5, 5th edition, O’Reilly Media, 2018. ISBN 978-1-491-97891-7. Targets PHP 5.4-7.1 and MySQL 5.6; only its PHP chapters were consulted. Companion code (6th edition): RobinNixon/lpmj6. Current edition: the 7th edition (2025).
The Laravel documentation (laravel.com/framework/docs/13.x), grouped as the documentation is:
-
Prologue: Release Notes and Upgrade Guide.
-
Getting Started: Installation, Configuration, Agentic Development, Directory Structure, Frontend, Starter Kits and Deployment.
-
Architecture Concepts: Request Lifecycle, Service Container, Service Providers and Facades.
-
The Basics: Routing, Middleware, CSRF Protection, Controllers, Requests, Responses, Views, Blade Templates, Asset Bundling, URL Generation, Session, Validation, Error Handling and Logging.
-
Digging Deeper: Artisan Console, Broadcasting, Cache, Collections, Concurrency, Context, Contracts, Events, File Storage, Helpers, HTTP Client, Images, Localization, Mail, Notifications, Package Development, Processes, Queues, Rate Limiting, Search, Strings and Task Scheduling.
-
Security: Authentication, Authorization, Email Verification, Encryption, Hashing and Password Reset.
-
Database: Getting Started, Query Builder, Pagination, Migrations, Seeding, Redis and MongoDB.
-
Eloquent ORM: Getting Started, Relationships, Collections, Mutators / Casts, API Resources, Serialization and Factories.
-
Testing: Getting Started, HTTP Tests, Console Tests, Browser Tests, Database and Mocking.
-
Packages: Cashier (Stripe), Cashier (Paddle), Envoy, Fortify, Folio, Head, Homestead, Horizon, Mix, Octane, Passport, Pennant, Pint, Precognition, Prompts, Pulse, Reverb, Sail, Sanctum, Scout, Socialite, Telescope and Valet.
Laravel project and first-party products
-
The release notes and upgrade guides of earlier versions, from 6.x to 12.x, and their sources in the laravel/docs repository.
-
The API reference, the framework source and releases, the application skeleton and the installer.
-
Laravel Learn and the starter kits, with the React starter kit and Wayfinder.
-
laravel/ai, laravel/mcp, laravel/boost and Tinker.
-
Livewire 4 and Flux; Inertia 3; Jetstream (legacy).
-
Laravel Shift, Rector with rector-laravel, and Laravel Lang.
The PHP Manual (php.net/manual), as the manual is organised:
-
Getting Started: Dealing with Forms.
-
Installation and Configuration: FastCGI Process Manager (FPM), its configuration and status page, Apache 2 on Unix systems and the core directives.
-
Language Reference: escaping from HTML, alternative syntax for control structures, variables from external sources and the predefined variables, including superglobals and
$_SERVER. -
Security: general considerations, filesystem, database and SQL injection, error reporting, user-submitted data, hiding PHP and keeping current.
-
Features: HTTP authentication, cookies, file uploads, connection handling, persistent database connections and the built-in web server.
-
Function Reference, the extensions used: PDO with its MySQL, PostgreSQL and SQLite drivers, MySQLi, Sessions, Filter, cURL,
php://wrappers and HTTP context options, Output Control, URI, GD, Imagick, Fileinfo, Password Hashing, Hash, Random, JSON, Mail, intl and OPcache, including preloading. -
FAQ: Safe password hashing.
-
Appendices: the PHP 8.1 deprecations among the migration guides.
php.net and the PHP project
-
The RFCs cited on individual pages, in the PHP RFC wiki: session security defaults, partitioned cookies (CHIPS), the bcrypt cost increase,
FILTER_THROW_ON_FAILUREand persistent cURL share handles. -
The PHP Internals Book on the PHP lifecycle.
PHP libraries, components and tooling
-
Symfony: the components (with HttpFoundation, Console, Process, VarDumper, Mailer and HttpClient) and the Symfony documentation.
-
Guzzle, Flysystem, Monolog, Carbon, phpdotenv, PsySH, FakerPHP, Intervention Image, PHPMailer, Nyholm PSR-7 and PSR-7 Server, FastRoute and league/oauth2-server.
-
Doctrine ORM, Slim 4 and Laminas Mezzio.
-
Composer and Packagist; Pest, including its browser testing; PCOV; Orchestra Testbench; spatie/laravel-package-tools.
-
Xdebug, Laravel Debugbar and ChromeDriver, with Playwright for comparison.
-
Community packages and tools named on the pages: Filament, Larastan, Lighthouse, Spatie Laravel Query Builder, spatie/laravel-permission, Scramble, L5-Swagger, Laravel Notification Channels and install-php-extensions.
-
Front end: Vite, Tailwind CSS, Alpine.js, htmx, shadcn/ui and Fontsource.
-
Diagrams: Mermaid entity relationship diagrams, the syntax of the Bookshelf schema diagram.
-
Services: the Pusher protocol, which Reverb implements, and the OpenAI Chat Completions API used by the AI SDK example.
-
The frameworks in the comparison table: Symfony, Slim, Mezzio, CakePHP 5, CodeIgniter 4, Yii, Ruby on Rails, and the Django, ASP.NET Core and Spring Boot sections of this site.
Servers, databases and infrastructure
-
FrankenPHP (with its worker mode, Laravel and Docker pages), RoadRunner and Swoole.
-
Nginx, Apache HTTP Server, Supervisor and Caddy.
-
PostgreSQL 17, MySQL 8.4, MariaDB, SQLite, Redis and Valkey, Laravel MongoDB and pgvector.
-
Mailpit and SeaweedFS, the local mail and S3 servers used to run the examples.
Specifications and standards
-
HTTP: RFC 9110 (HTTP semantics), RFC 9457 (problem details), RFC 5861 (stale content), RFC 8594 (Sunset), RFC 9745 (Deprecation), RFC 7617 (Basic authentication) and RFC 6570 (URI templates); cookies in RFC 6265; URIs in RFC 3986 and the WHATWG URL Standard.
-
Real time: RFC 6455 (WebSocket) and WHATWG server-sent events.
-
Identity: RFC 6749 (OAuth 2.0), RFC 7636 (PKCE), the OAuth 2.1 draft, Web Authentication Level 3, NIST SP 800-63B, NIST RBAC and the Pwned Passwords API.
-
Browser security: Content Security Policy Level 3, RFC 6797 (HSTS) and
Sec-Fetch-Site. -
Data: JSON:API, OpenAPI 3.1, RFC 9562 (UUIDs), ULID, RFC 5545 (iCalendar) and RFC 5424 (syslog).
-
PHP-FIG: PSR-7, PSR-11, PSR-15, PSR-17 and PSR-18; Semantic Versioning.
-
Accessibility: the W3C ARIA Authoring Practices Guide, for the roles and attributes of the Blade components.
-
AI: the Model Context Protocol specification and OWASP LLM01 Prompt Injection.
-
OWASP: the Top 10:2025 and the Cheat Sheet Series pages for PHP configuration, Laravel, XSS prevention, SQL injection prevention, CSRF prevention, session management, file upload, password storage, authentication, forgot password, authorization, input validation, SSRF prevention and HTTP headers.
-
Patterns: Martin Fowler’s Active Record, Value Object and Domain Event, and Pete Hodgson’s Feature Toggles.
-
Linux manual pages: crontab(5) and execve(2).
-
PHP The Right Way, as a community reference.