
What you need
- Computer and internet: a laptop or desktop and a stable connection
- System: Windows 10 or 11, macOS or Linux
- Before this: How the web works, Your first Laravel route and Build a REST API
Download only from each tool's official site and check the address before installing.
What you will learn
You will learn the ten most common ways web applications get attacked, in plain words, with a small example of each and the habit that prevents it in Laravel. The list follows the OWASP Top 10:2025, the most widely used ranking of web application security risks.
Level: intermediate. You should be comfortable with How the web works, Your first Laravel route and Build a REST API. Each risk below links to where you practise the fix, and at the end you run three small safe demos on your own computer.
Your folder for this lesson: ~/ewoi-learning/security-basics (you create it in the hands-on part). The finished files are in the step folder on GitHub, so you can compare your work.

Security is not a separate skill for experts. It is a set of habits every developer uses daily. By the end you will know the ten habits that matter most.
The big picture in one sentence
Almost every web attack comes from the app trusting something it should not: a user, an input, a setting, a library or its own assumptions.
How to read this lesson
For each risk you get four short parts:
| Part | Question it answers |
|---|---|
| What it is | The risk in plain words |
| An example | What it looks like in real code |
| The habit | What you do to prevent it |
| In Laravel | The tool that helps |
A01 Broken access control
What it is: a user can see or change something they should not. It has been number one for years because it is easy to forget a single check.
An example: your app shows an invoice at /invoices/1042. A signed-in user changes the number to 1043 and sees someone else's invoice. This is called an IDOR (insecure direct object reference), one form of broken access control.
// Unsafe: anyone signed in can open any invoice
Route::get('/invoices/{invoice}', fn (Invoice $invoice) => view('invoice', compact('invoice')));
The habit: for every request, ask "is this user allowed to do this to this record?" and deny by default.
In Laravel: policies and Gate::authorize, or query through the user's own records:
Route::get('/invoices/{invoice}', function (Invoice $invoice) {
Gate::authorize('view', $invoice);
return view('invoice', compact('invoice'));
})->middleware('auth');
Cross-site request forgery (CSRF) belongs here too: another site makes a signed-in visitor's browser send a request they never meant to, such as "delete my account". Laravel blocks it by checking a secret token on every form (@csrf); in Laravel 13 it first checks the browser's Sec-Fetch-Site header, which says whether a request came from your own site.
This category also includes SSRF: tricking your server into requesting an address the attacker chooses, such as an internal admin service. If your app fetches a URL a user gave you (for example "import from link"), only allow the hosts you expect.
A02 Security misconfiguration
What it is: the code is fine, but a setting is not. It jumped to second place in 2025.
Examples: debug mode left on in production, so error pages show passwords; default admin accounts; directory listings switched on; a storage bucket open to the world; missing security headers.
The habit: production settings are reviewed like code, and the app refuses to start with dangerous ones.
In Laravel: APP_DEBUG=false and APP_ENV=production on live servers, the web server pointed at the public folder only, and .env never reachable from the browser. Our article Why your first deploy fails covers these.

A blank, friendly error page for visitors and a detailed log for you: that is the right split. Never the other way round.
A03 Software supply chain failures
What it is: your app is only as safe as the packages, tools and services it depends on. In 2025 this grew out of the older "vulnerable and outdated components" category to cover the whole chain (packages, build tools and the services that deliver them), because attacks on popular packages keep growing.
Examples: an outdated package with a known hole; a fake package with a name one letter different from a real one; a compromised build tool.
The habit: fewer, well-known dependencies; keep them updated; check for known vulnerabilities on every change; commit the lock files.
In Laravel:
composer audit npm audit --audit-level=high
These commands compare your installed packages with public lists of known vulnerabilities. Run each one inside your project folder: composer audit checks PHP packages from composer.lock, and npm audit --audit-level=high checks JavaScript packages from package-lock.json and only fails on high or critical problems. Expected output when all is well: No security vulnerability advisories found. and found 0 vulnerabilities. If a package is listed, update it (composer update vendor/package) and run the command again. Run them in your automated checks, not just once.
A04 Cryptographic failures
What it is: sensitive data is not protected properly, at rest or in transit.
Examples: passwords stored in plain text or with a fast hash; a site without HTTPS; personal data sent to a log file; home-made encryption.
The habit: HTTPS everywhere; passwords hashed with a slow function; other sensitive fields encrypted with well-tested tools; never invent your own crypto.
In Laravel: Hash::make and the hashed cast for passwords (see Hash passwords properly), and the encrypted cast for other sensitive columns (for example 'id_number' => 'encrypted' in a model's casts), which locks the value with your app's APP_KEY before saving it. Keep APP_KEY secret and backed up: if you lose it, encrypted columns can no longer be read.
A05 Injection
What it is: user input is treated as code. This includes SQL injection, command injection and cross-site scripting (XSS).
SQL injection example:
// Unsafe: the input becomes part of the SQL
DB::select("SELECT * FROM users WHERE email = '".$request->input('email')."'");
If someone types ' OR '1'='1, the query returns every user.
The fix: parameters (also called bindings, or a prepared statement), which send the input separately from the SQL so it can never change the query's meaning:
DB::select('SELECT * FROM users WHERE email = ?', [$request->input('email')]);
User::where('email', $request->input('email'))->first();
Laravel's query builder and Eloquent use bindings automatically.
XSS example: a comment containing <script> runs in every visitor's browser if you print it raw. In Blade, {{ $comment }} escapes it safely; {!! $comment !!} prints it raw, so use {!! !!} only for HTML you created and trust.
Ask your AI assistant
Explain SQL injection and XSS to me as a beginner using one tiny example each, then show me how Laravel's query builder and Blade's {{ }} prevent them. Do not give me attack payloads beyond the simplest classic example.
A06 Insecure design
What it is: the plan itself is unsafe, so even perfect code cannot fix it.
Examples: a password reset that only asks for an email and a birth date; a checkout that trusts the price sent by the browser; no limit on how many times someone can guess a one-time code.
The habit: think like an attacker before you build. For each feature ask: what could go wrong, who could abuse it, and what is the worst outcome? Write the answer down and design the protection in.
In Laravel: compute prices on the server, rate limit sensitive actions with the throttle middleware, and keep state changes (such as "paid") behind server-side checks, as in the M-Pesa tutorial.
A07 Authentication failures
What it is: weaknesses in how users prove who they are.
Examples: unlimited password guesses (brute force); weak or known-leaked passwords allowed; sessions that never expire; password reset links that never expire or can be reused.
The habit: use a proven sign-in system instead of writing your own; limit attempts (rate limiting); offer two-step sign-in; expire sessions and reset links.
In Laravel: the official starter kits (they already limit sign-in attempts and offer two-step sign-in), the throttle middleware on other sensitive routes, the Password::min(15)->uncompromised() rule and signed, expiring links.
A08 Software or data integrity failures
What it is: trusting code or data that could have been changed on the way.
Examples: loading a script from a site you do not control without checking it; accepting a "payment successful" message without verifying it; unserialising data a user sent you.
The habit: verify before you trust: check signatures or confirm with the source, pin versions, and never unserialise untrusted input.
In Laravel: confirm payment results with the provider's status query (the M-Pesa tutorial does this), verify webhook signatures when the provider offers them, and use JSON instead of PHP serialisation for data that crosses a boundary.
A09 Security logging and alerting failures
What it is: attacks happen and nobody notices, or the logs are useless when they are needed. Renamed in 2025 to stress alerting: logs nobody reads do not protect anyone.
Examples: no record of failed sign-ins; logs that contain passwords; no alert when an admin account changes.
The habit: log security events (sign-ins, failures, permission changes) without secrets, keep them safe, and alert a person on the important ones.
In Laravel: the Log facade with context arrays, masking personal data (2547****4149), and a log channel or error tracker that notifies you.
A10 Mishandling of exceptional conditions
What it is: the app behaves unsafely when something unexpected happens. New in 2025.
Examples: an error halfway through a payment leaves an order paid but not recorded; a failed check "fails open" and lets the request through; an error message reveals internal details.
The habit: fail closed (when in doubt, deny), wrap related changes in database transactions, and show users a generic message while logging the details.
In Laravel: DB::transaction(...), authorisation checks that deny on any error, and the default production error pages.
The ten habits on one page
| # | Risk | The habit |
|---|---|---|
| A01 | Broken access control | Check permission on every request, deny by default |
| A02 | Security misconfiguration | Safe production settings, reviewed like code |
| A03 | Supply chain failures | Few, updated, audited dependencies |
| A04 | Cryptographic failures | HTTPS, slow password hashing, proven crypto only |
| A05 | Injection | Bindings for SQL, escaping for HTML |
| A06 | Insecure design | Think like an attacker before building |
| A07 | Authentication failures | Proven sign-in, limits, two-step, expiry |
| A08 | Integrity failures | Verify before you trust |
| A09 | Logging and alerting failures | Log security events, alert a person |
| A10 | Exceptional conditions | Fail closed, use transactions |
Try it: three safe fixes on your own computer
Reading about attacks is one thing; watching the fix work is what makes it stick. You will run three tiny PHP files. Each one describes the unsafe pattern at the top and runs only the safe version, so nothing here attacks anything.
1. Create your folder. Open your terminal and run:
mkdir -p ~/ewoi-learning/security-basics cd ~/ewoi-learning/security-basics
mkdir -p makes the folder (and ~/ewoi-learning if it does not exist yet); cd moves you into it. Every command below runs from this folder.
2. Add the three files. Open the step folder on GitHub, open each file, press the "Copy raw file" button and save it in your folder with the same name:
| File | What it shows |
|---|---|
01-sql-prepared-statements.php |
A prepared statement: the input is sent separately from the SQL |
02-escape-output.php |
Escaping: <script> is shown as text instead of running |
03-csrf-token.php |
A CSRF token: a form is accepted only with the secret token |
The heart of each file is short. The safe query:
$statement = $pdo->prepare('SELECT name FROM users WHERE email = ?');
$statement->execute([$email]);
The ? is a placeholder. prepare sends the SQL to the database first, and execute sends the input afterwards as plain data, so a quote or the word OR inside it is just text. The safe output:
htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
This turns <, >, quotes and & into harmless codes such as <, so the browser shows them instead of running them. The token check:
hash_equals($session['csrf_token'], $submitted);
hash_equals compares the token from the form with the one saved in the visitor's session, in constant time, so the comparison does not leak how many characters matched.
3. Run them.
php 01-sql-prepared-statements.php php 02-escape-output.php php 03-csrf-token.php
Expected output (the important lines):
Search for: [email protected] Result: Amina Search for: ' OR '1'='1 Result: no user found Sent to the browser: <script>alert('hi')</script> Nice post! Form with the right token: accepted Form with no token: rejected Form with a guessed token: rejected
The classic injection text found nobody, because the database searched for a user whose email is literally ' OR '1'='1. If you see php: command not found, PHP is not installed or not on your path: finish the set-up in Your first Laravel route first. If you see could not find driver, your PHP is missing the SQLite extension; search for "PHP enable pdo_sqlite" for your operating system.
4. Try them in the browser. Start PHP's built-in server:
php -S localhost:8000
Open http://localhost:8000/01-sql-prepared-statements.php and search for an email, then open the other two files the same way. In 03-csrf-token.php, the button with the token is accepted and the button without it is rejected. Press Ctrl+C in the terminal to stop the server.
5. Commit your work.
git init git add 01-sql-prepared-statements.php 02-escape-output.php 03-csrf-token.php git commit -m "Add safe demos for SQL injection, XSS and CSRF"
git init turns the folder into a Git repository (skip it if you already did), git add lists the three files by name, and git commit saves them with a message. You now have a working, committed folder to return to.

Notice that every fix is boring: one placeholder, one function call, one comparison. Good security usually is.
Recap
- Most attacks exploit something the app trusted without checking.
- Access control, configuration and dependencies are the top risks in 2025, ahead of classic injection.
- Laravel prevents many risks by default (bindings, escaping, CSRF tokens, hashing), but only if you do not bypass it.
- The safe patterns are small: prepared statements, escaped output, a checked token.
- Security is a habit you apply to every feature, not a final step.
Your practice task
Take one of your own projects (the task tracker is perfect) and check it against the table above. For each row, write "safe", "not safe" or "not sure", with the file and line. Then fix one "not safe" item, using the hands-on Secure a Laravel app walkthrough as your guide.
Ask your AI assistant
Act as a security reviewer. Here is one Laravel controller from my own project: [paste it]. Check it against the OWASP Top 10:2025 categories and list any risks in order of severity, explaining each in simple words and showing the safer code. Do not change the parts that are already safe.
Check your understanding

Every lesson stays free. Tap the thumbs up so we know what works, or say thanks with a soda or a coffee: it pays for hosting and new lessons.


