Semantic structure, accessible forms, media performance, and native dialogs.
Learn to Code — CodePrimer
A classroom encyclopedia of HTML5, CSS3, JavaScript, PHP 8, SQL, and Laravel. Search a guide, then follow the learning path from beginner to advanced.
Selectors, the box model, Flexbox, Grid, responsive layout, and modern CSS.
Language fundamentals, the DOM, events, async code, fetch, storage, and modules.
Types, functions, objects, superglobals, passwords, and PDO prepared statements.
Tables, queries, joins, indexes, foreign keys, CTEs, and normalization.
Routing, Blade, validation, Eloquent, auth, queues, and production Laravel patterns.
Showing closest & fuzzy matches for your search.
HTML5 Document Structure: DOCTYPE, Head, and Body
How do I write a valid HTML5 document from scratch?
HTML Charset, Viewport, and SEO Meta Tags
Which meta tags belong in the head of every HTML page?
HTML Headings and a Logical Document Outline
How should h1 through h6 be used so the outline stays logical?
HTML Paragraphs, Line Breaks, and Readable Text
When should I use a paragraph instead of a br line break?
HTML5 Semantic Landmarks: header, nav, main, and footer
How do I structure header, nav, main, article, section, aside, and footer?
ARIA Basics: Roles, Labels, and When Not to Use Them
When should I add ARIA, and when is native HTML enough?
HTML Links: href, Absolute and Relative URLs, and rel
How do I write accessible links with safe href and rel values?
HTML Lists: ul, ol, dl, and Nested Navigation
How do I mark up unordered, ordered, and description lists?
HTML Images and alt Text for Accessibility and SEO
How do I write alt text that helps screen readers and image search?
Responsive Images with picture, srcset, and lazy Loading
How do I serve sharp images without wasting mobile bandwidth?
HTML Script Loading with defer, async, and type=module
How do I load JavaScript without blocking HTML parsing?
Accessible HTML Forms, Input Types, and Native Validation
How do I build a form with labels, input types, and native validation?
HTML Button Types: submit, button, and reset
Why does a button submit the form when I only wanted a click?
HTML Form Methods: GET versus POST
When should a form use GET instead of POST?
Accessible HTML Tables with thead, tbody, and scope
How do I associate table headers with their cells?
HTML data-* Attributes and the dataset API
How do I store small configuration values on an element?
HTML Disclosure Widgets with details and summary
How do I build a native accordion without JavaScript?
Accessible Modals with the HTML dialog Element
How do I open an accessible modal with the dialog element?
HTML figure and figcaption for Captioned Media
How do I attach a caption to an image or a code sample?
HTML time Element for Dates
How do I mark a date so machines and people can both read it?
Fieldset and Legend for Form Groups
How do I label a group of related radio buttons?
Sandboxed iframes
How do I embed a page without giving it your site privileges?
Open Graph Meta Tags
Which meta tags control a link preview title and image?
The HTML template Element
How do I store inert markup to clone with JavaScript?
progress and meter Elements
How do I show a completion amount in HTML?
Autocomplete Tokens on Inputs
How do I help browsers fill a checkout form correctly?
The HTML mark Element for Search Highlights
How do I mark words that matched a search?
HTML datalist for Suggested Input Values
How do I suggest track names without a closed dropdown?
The HTML Popover API
How do I open a small note without a dialog script?
The HTML search Landmark
How do I mark the site search form as a landmark?
The HTML download Attribute
How do I offer a file save instead of navigation?
inputmode for the Right Mobile Keyboard
How do I open a numeric keyboard without type=number?
The spellcheck Attribute
How do I turn spell checking off for code and on for prose?
The HTML output Element
How do I show a calculated result inside a form?
Hidden Fields and What Not to Trust
What is a hidden input for, and what must the server ignore?
The wbr Element for Optional Breaks
How do I let a long path wrap without adding spaces?
Link an external CSS file
How do I attach a stylesheet?
div vs span
When do I use div or span?
Radio button group
How do I let users pick only one option?
Checkboxes as PHP arrays
How do I submit multiple checkboxes to PHP?
Select dropdown
How do I make a dropdown menu?
Textarea multi-line input
How do I collect long comments?
Date, hidden, and file inputs
What special input types should I know?
Audio and video embeds
How do I embed media without Flash?
Internal CSS with style tag
How do I put CSS inside the HTML file?
Semantic navigation bar
How do I mark up a site nav?
Explicit label for= binding
How do I connect a label to an input?
Figure with caption
How do I caption an image semantically?
Embed with iframe
How do I embed another page or map?
Three Ways to Apply CSS: Inline, Internal, and External
How do I attach CSS to an HTML page?
CSS Selectors: Elements, Classes, Descendants, and Groups
Which CSS selector should I use to target an element?
CSS Specificity: Classes, IDs, and !important
Why does my CSS rule lose to another rule?
The CSS Box Model and border-box Sizing
How do width, padding, border, and margin add up?
CSS Margin, Padding, and Margin Collapse
When does vertical margin collapse, and how do I space elements?
CSS Flexbox: Direction, Alignment, Gap, and Grow
How do I lay out a row of items with Flexbox?
CSS Flex Wrap and Gap for Wrapping Toolbars
How do I let flex items wrap without float hacks?
Center an Element with Flexbox
How do I center a box horizontally and vertically?
CSS Grid Two-Column Layout with a Sidebar
How do I build a content column and a sidebar with Grid?
CSS Grid: minmax, auto-fit, and grid-template-areas
How do I make a responsive card grid without media queries?
CSS Positioning: relative, absolute, fixed, sticky, and z-index
How do relative, absolute, fixed, and sticky positioning differ?
Responsive CSS with Media Queries
How do I change layout at phone, tablet, and desktop widths?
CSS Container Queries with @container
How do I style a component based on its container, not the viewport?
CSS Custom Properties and var()
How do I share colors and spacing with CSS variables?
Fluid Typography with clamp()
How do I scale font size between a phone and a desktop without a stack of media queries?
CSS Transitions for Hover and Focus
How do I animate a color or transform without JavaScript?
CSS Keyframe Animations
How do I define a reusable @keyframes animation?
Modern CSS Selectors: :has(), :is(), and :where()
How do :has(), :is(), and :where() change selector lists and specificity?
CSS object-fit and object-position for Replaced Media
How do I crop a photo inside a fixed box without stretching it?
CSS aspect-ratio for Stable Media Frames
How do I reserve a 16:9 box before the image arrives?
CSS Logical Properties
How do I write margin and padding that follow writing direction?
CSS Cascade Layers with @layer
How do I control stylesheet order without raising specificity?
Native CSS Nesting
How do I nest selectors in plain CSS?
:focus-visible for Keyboard Focus
How do I style keyboard focus without a ring on every mouse click?
CSS Scroll Snap
How do I make a horizontal card row snap into place?
CSS Subgrid
How do I align nested grid items to the parent tracks?
CSS line-clamp for Card Blurbs
How do I cut a paragraph after two lines with an ellipsis?
CSS text-wrap for Headings
How do I stop a heading from leaving one word on the last line?
CSS accent-color for Form Controls
How do I tint checkboxes and range inputs to match the catalog?
CSS color-mix for Tinted Surfaces
How do I tint a surface with a brand color without a preprocessor?
CSS overflow for Long Code and Menus
How do I scroll a code sample without stretching the page?
CSS filter for Image States
How do I grayscale an image until it is hovered?
CSS outline and outline-offset
How do I draw a focus ring that does not shift layout?
CSS user-select for Copyable and Locked Text
How do I stop a button label from being highlighted when it is double-clicked?
CSS writing-mode for Vertical Labels
How do I set a vertical spine label without rotating the whole card?
CSS scrollbar-gutter
How do I stop a list from shifting when a scrollbar appears?
CSS list-style and Counters
How do I number lesson steps without typing the numbers?
CSS cursor for Controls
How do I show a pointer on a clickable card but not on plain text?
CSS appearance for Native Controls
How do I restyle a select without losing the control?
CSS hyphens for Narrow Columns
How do I break long words in a narrow lesson column?
CSS isolation for Stacking Contexts
How do I stop a card shadow from mixing with a popup z-index?
display block inline flex
How does display change layout?
Hover and focus-visible
How do I style hover and keyboard focus?
Truncate long text with ellipsis
How do I cut overflow text with …?
Simple CSS reset start
How do I normalize browser defaults a bit?
Space-between header layout
How do I put logo left and links right?
JavaScript const, let, Scope, and Hoisting
How do const and let differ from var?
Destructuring, Spread, and Rest in JavaScript
How do I unpack objects and arrays and copy them without mutation?
JavaScript Array Methods: map, filter, reduce, find, some, every
How do I transform and test arrays without a manual loop?
document.getElementById and Null Checks
How do I select one element by id and handle a missing node?
querySelector for CSS-Style DOM Lookups
How do I select one element with a CSS selector?
querySelectorAll and Iterating a NodeList
How do I select every matching element and loop them?
textContent versus innerHTML and XSS
When is innerHTML dangerous, and what should I use instead?
classList add, remove, toggle, and contains
How do I change classes without rewriting the class attribute?
createElement, textContent, and append
How do I build DOM nodes without HTML strings?
DocumentFragment for Batch DOM Updates
How do I insert many nodes without reflowing on every append?
A Click Handler that Updates the Page
How do I run JavaScript when a button is clicked?
Event Delegation with addEventListener
How do I handle clicks on many rows with one listener?
FormData, submit Events, and Client-Side Checks
How do I read a form with FormData and stop a bad submit?
Promises, async/await, and try/catch
How do I wait for an asynchronous result without callback pyramids?
fetch JSON: GET, POST, Headers, and Errors
How do I GET and POST JSON with fetch and handle HTTP errors?
localStorage and sessionStorage with JSON
How do I save a small object in the browser and read it back?
Debounce and Throttle Event Handlers
How do I stop a search input or scroll handler from running too often?
ES Modules: import, export, and type=module
How do I split browser JavaScript into modules?
Optional Chaining and Nullish Coalescing
How do I read a nested property when a middle object might be missing?
URLSearchParams for Query Strings
How do I read and build a query string in the browser?
IntersectionObserver for Lazy Sections
How do I run code when an element scrolls into view?
AbortController for fetch
How do I cancel a fetch when the user types again?
CustomEvent for Component Messages
How do I dispatch a named event from a widget?
The Clipboard API
How do I copy text with navigator.clipboard?
Intl for Numbers and Dates
How do I format a price and a date for a locale?
history.pushState for Filters
How do I update the query string without reloading?
JavaScript Map and Set
When should I use Map or Set instead of a plain object?
structuredClone for a Real Copy
How do I copy a lesson object without sharing nested arrays?
ResizeObserver for Responsive Components
How do I react when a card changes width, not the window?
The Page Visibility API
How do I pause work when the student switches tabs?
crypto.randomUUID for Client Ids
How do I create an id in the browser without a library?
TextEncoder and TextDecoder
How do I turn a string into UTF-8 bytes in the browser?
Error cause in JavaScript
How do I wrap a failed fetch without losing the original error?
Array at, findLast, and toSorted
How do I read the last item and sort a copy of an array?
Template Literals
How do I build a sentence from a title and a seat count?
requestAnimationFrame
How do I animate a progress bar without setInterval?
Object.hasOwn
How do I check that a lesson object has its own seats field?
The URL Class
How do I build a lesson URL without string concatenation?
Arrow function event listener
Can I use an arrow function for events?
Live input event
How do I react as the user types?
change event on select
How do I detect dropdown changes?
setAttribute and style
How do I change attributes and CSS from JS?
Remove a DOM node
How do I delete an element?
Read input/select/textarea values
How do I read form field values in JS?
Read data-* with dataset
How do I read data-price in JavaScript?
mouseover tooltip style
How do I run code on hover?
Keyboard keydown shortcut
How do I listen for a key press?
JavaScript ternary operator
How do I write a one-line if/else?
Classic for loop
How do I loop a fixed number of times?
for...of over an array
How do I loop array values cleanly?
JavaScript object basics
How do I store keyed data in JS?
Wait for DOMContentLoaded
Why is getElementById null?
Block empty form fields in JS
How do I stop submit when a field is blank?
Embedding PHP in HTML with Standard Tags
How do I open and close PHP so HTML stays valid?
PHP Comments: Line, Block, and Docblocks
How do I comment PHP without commenting out the wrong lines?
PHP Variable Names, Assignment, and Scope Rules
What are the rules for PHP variable names, values, and scope?
PHP Types: Strings, Ints, Floats, Bools, Null, and Arrays
What are the core PHP types and how do I inspect them?
declare(strict_types=1) and Type Juggling
How do I stop PHP from silently coercing function arguments?
PHP Strings: Concatenation, Interpolation, and Multibyte Length
How do I build and measure strings safely in PHP 8?
DateTimeImmutable for Time Zones and Formatting
How do I handle dates in PHP without mutating a shared clock?
PHP Functions, Parameters, Return Types, and Defaults
How do I write a PHP function with a return type?
PHP Closures, Arrow Functions, and use()
How do I pass a small function to array_map or array_filter?
PHP Associative Arrays and Nested Records
How do I store a student record in an associative array?
array_map, array_filter, and array_column
How do I reshape a list of rows without a manual index loop?
PHP Classes, Constructors, and Property Promotion
How do I model a Student with a promoted constructor?
PHP Inheritance, Interfaces, and Contracts
When should I use an interface instead of extending a base class?
$_POST, Output Escaping, and XSS Prevention
How do I read a POST form and escape it before HTML?
password_hash and password_verify
How do I store a password so a database leak is not the password?
json_encode, json_decode, and JSON_THROW_ON_ERROR
How do I return and parse JSON in PHP without silent failures?
PHP PDO Error Mode: Exceptions Instead of Silent Failures
How should PDO report database errors in PHP 8?
PHP PDO SELECT with a Prepared Statement
How do I SELECT a row by id without concatenating SQL?
PHP PDO INSERT with Prepared Statements
How do I insert a row with PHP PDO without SQL injection?
PHP PDO UPDATE with a WHERE Clause
How do I update one row without changing the whole table?
PHP PDO DELETE with a WHERE Clause
How do I delete one row safely with PDO?
PDO Transactions: beginTransaction, commit, and rollBack
How do I insert a student and an enrollment so both succeed or neither does?
Composer and PSR-4 Autoloading
How do I autoload PHP classes with Composer instead of a pile of require calls?
PHP 8.1 Enums
How do I represent a fixed set of tracks with an enum?
PHP match Expressions
How do I map a value with match instead of switch?
The PHP Nullsafe Operator
How do I call a method when the object might be null?
PHP Exceptions and finally
How do I throw and catch a domain exception?
PHP Sessions for a Signed-In User
How do I store a user id in $_SESSION safely?
filter_var for Email and Integers
How do I validate an email and an integer with filter_var?
preg_match for a Slug
How do I test that a slug contains only lowercase letters and hyphens?
PHP Named Arguments
How do I call a function with named arguments so defaults stay clear?
PHP Union Types
How do I accept an int or a numeric string without turning types off?
PHP str_contains, str_starts_with, and str_ends_with
How do I test a string without strpos tricks?
PHP Readonly Properties
How do I stop a lesson id from being changed after construction?
PHP json_validate
How do I check a JSON string without decoding it into an array?
password_needs_rehash
How do I upgrade a stored password hash when the algorithm changes?
PHP Headers and Output
How do I send a status and a redirect before any HTML?
PHP Randomizer for Unbiased Picks
How do I pick a lesson at random without a biased modulo?
PHP Array Destructuring
How do I unpack the first two lessons from a list?
PHP Attributes
How do I attach metadata to a class without a comment parser?
PHP First-class Callables
How do I pass a function to array_map without a string name?
mb_substr for Multibyte Titles
How do I shorten a title without splitting a character?
number_format and Intl for Prices
How do I print a seat price with grouping and two decimals?
echo vs print
Should I use echo or print?
Debug with var_dump
How do I inspect a variable’s type?
PHP math helpers
How do I do min/max/round/random in PHP?
PHP type casting
How do I cast a value to another type?
PHP arithmetic operators
What are PHP math operators?
PHP comparison operators
What is == vs === in PHP?
PHP logical operators
How do I combine conditions?
Combined assignment operators
What does += mean in PHP?
if / elseif / else
How do I branch logic in PHP?
Ternary and ??
How do I assign with a short conditional?
switch statement
How do I handle many discrete cases?
while loop
How do I loop while a condition is true?
do...while loop
How do I run a loop at least once?
for loop
How do I loop with a counter?
foreach over arrays
How do I loop an array in PHP?
Default function arguments
How do I make a parameter optional?
Indexed arrays
How do I store a list in PHP?
Read $_GET values
How do I read query string data?
Read checkbox array in PHP
How do I read skills[] from a form?
Destroy a PHP session
How do I log a user out?
require db.php connection
How do I reuse one DB connection file?
Redirect with header Location
How do I send the browser to another page?
Detect GET vs POST in PHP
How do I know which HTTP method was used?
Reuse header with include
How do I share a header across pages?
Local vs global scope
Why can’t my function see an outside variable?
Static variable in a function
How do I keep a value between function calls?
Multidimensional arrays
How do I store rows of data?
Sanitize and validate input
How do I protect against XSS and bad emails?
PDO connection for Laragon MySQL
How do I connect PHP to Laragon MySQL?
PDO fetch all rows
How do I list records from MySQL?
CREATE DATABASE and Character Set utf8mb4
How do I create a MySQL database that stores Unicode correctly?
CREATE TABLE with Keys, NOT NULL, UNIQUE, and Defaults
How do I create a table with the right data types and constraints?
ALTER TABLE to Add, Modify, and Index a Column
How do I add a column to a table that already has rows?
INSERT and UPDATE Rows with an Explicit WHERE
How do I insert a user and update that same row safely?
DELETE a Single Row with WHERE
How do I delete one row without emptying the table?
SELECT, WHERE, and Comparison Predicates
How do I read specific rows from a MySQL table?
ORDER BY with LIMIT and OFFSET Pagination
How do I page through sorted SQL results?
COUNT, SUM, AVG, GROUP BY, and HAVING
How do I total and filter groups in SQL?
INNER JOIN Across Users, Courses, and Enrollments
How do I combine matching rows from related tables?
LEFT JOIN to Keep Rows with No Match
How do I list every user even when they have no enrollment?
Indexes, Composite Indexes, and EXPLAIN
How do I index a WHERE/ORDER BY so MySQL does not scan the whole table?
Foreign Keys, ON DELETE CASCADE, and ON DELETE SET NULL
How do I stop orphan enrollment rows?
Subqueries in WHERE and in the SELECT List
How do I filter rows using a nested SELECT?
Common Table Expressions with WITH
How do I name a subquery so a report is readable?
Database Normalization: 1NF, 2NF, and 3NF
How do I split repeating course lists out of a user row?
SQL Transactions: START TRANSACTION, COMMIT, ROLLBACK
How do I make two writes succeed or fail together?
CASE Expressions in SELECT
How do I turn a status code into a label in SQL?
UNION of Two Result Sets
How do I stack two SELECT results in one list?
CREATE VIEW for a Roster
How do I save a SELECT as a view?
ROW_NUMBER and SUM Over a Window
How do I rank rows without collapsing them with GROUP BY?
INSERT ... ON DUPLICATE KEY UPDATE
How do I insert a row or update it when the unique key exists?
CHECK Constraints
How do I reject a seat count outside 1 to 40 in the table itself?
MySQL Date Functions
How do I filter rows from the last seven days?
SQL EXISTS for a Membership Test
How do I find lessons that have at least one confirmed seat?
COALESCE and NULLIF
How do I show a fallback when a column is null?
SQL CAST and CONVERT
How do I compare a numeric string column as a number?
SELECT DISTINCT
How do I list each track once?
TRUNCATE versus DELETE
When should I empty a table with TRUNCATE instead of DELETE?
SQL BETWEEN and IN
How do I filter lessons by a seat range or a list of tracks?
MySQL JSON Extract
How do I read a field inside a JSON column?
SQL INTERSECT
How do I find users who both teach and enroll?
SQL LIKE and Escaped Wildcards
How do I search lesson titles without treating a percent sign as a wildcard?
CHAR_LENGTH and LENGTH
How do I measure a title in characters instead of bytes?
LIKE search pattern
How do I search text with a keyword?
WHERE with AND / OR
How do I combine filters in SQL?
COUNT with GROUP BY
How do I count rows per category?
Basic transaction
How do I commit or roll back multiple writes?
Laravel Routes: URLs, Names, Parameters, and Groups
How do I declare web and API routes in Laravel?
Laravel Route Model Binding
How does Laravel turn a URL id into an Eloquent model?
Laravel Controllers and Single Action Controllers
How do I move route logic into a controller?
Blade Layouts, Loops, CSRF, and Components
How do I render a layout and a safe form in Blade?
Form Request Validation in Laravel
How do I validate a form and keep the controller thin?
Eloquent CRUD: Create, Read, Update, and Delete
How do I create, find, update, and delete a Lesson with Eloquent?
Eloquent Relationships: hasMany and belongsTo
How do I relate lessons, enrollments, and users?
Laravel Eloquent Eager Loading (with) to Prevent N+1 Queries
How do I prevent N+1 database queries in Laravel Eloquent?
Laravel Migrations and the Schema Builder
How do I version a lessons table with a Laravel migration?
Laravel Seeders and Model Factories
How do I generate realistic lesson rows for local development?
Auth Middleware and Guest Routes in Laravel
How do I restrict a route to signed-in users?
Laravel Gates and Policies
How do I authorize an update so users only edit their own lesson?
Laravel File Storage on the Public Disk
How do I validate an upload and store it on the public disk?
Laravel Pagination with the Query String
How do I paginate lessons and keep the search query?
Laravel API Resources
How do I shape JSON for a lesson and its enrollments?
Query Scopes and Attribute::make
How do I reuse a published() scope and format a title?
Laravel Queues and Jobs
How do I queue a slow enrollment email?
Laravel Task Scheduling
How do I run a command every morning?
Laravel Rate Limiting
How do I throttle a login or search endpoint?
The Laravel HTTP Client
How do I call another JSON API from a Laravel action?
Laravel Cache for a Catalog Count
How do I cache an expensive count without serving it forever?
Laravel Soft Deletes
How do I hide a lesson without removing the row?
Laravel Logging
How do I record a catalog failure without showing it to the student?
Laravel Events and Listeners
How do I run follow-up work when a lesson is published without stuffing it in the controller?
Laravel Attribute Casts
How do I get a Carbon date and a boolean from a lesson row?
Laravel Mail
How do I send a short enrollment note without building the message in the controller?
Laravel Signed URLs
How do I share a temporary lesson link that fails if someone edits the query?
Laravel Collections
How do I group lessons by track after they are loaded?
A Custom Laravel Validation Rule
How do I reject a lesson slug that is not lowercase hyphenated words?
A Custom Laravel Middleware Alias
How do I require an instructor role on a group of routes?
Laravel config and env
Where should a seat limit live so it is not hardcoded in a controller?
Laravel Session Flash Data
How do I show a one-time saved message after a redirect?
Laravel Notifications
How do I notify a user on the database channel and by mail from one class?
No guides matched that search.
Try a shorter keyword, a synonym (like js or db), or remove a filter.