Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 67 ยท Security, Errors and Deployment

Security in Laravel

Learn how Laravel protects against CSRF, XSS, SQL injection and mass assignment, and how to use encryption, rate limiting, security headers and safe uploads.

Laravel gives you secure defaults for many common attacks: forms need a CSRF token, Blade escapes output, the query builder uses bound parameters and cookies are encrypted. The framework only protects you while you use those features as intended. Most real Laravel vulnerabilities come from switching a protection off: printing raw HTML, concatenating SQL, using $guarded = [], or trusting an uploaded file name.

This lesson walks through the attacks you must know and the Laravel feature that answers each one. It builds on Security Basics in PHP, which explains the attacks themselves. The Laravel code is read-only; the runnable examples show SQL bindings against concatenation and a CSRF-style token check in plain PHP.

The threats at a glance

flowchart TD
    R["Incoming request"] --> A["CSRF: forged form posts"]
    R --> B["XSS: injected scripts in output"]
    R --> C["SQL injection: input inside queries"]
    R --> D["Mass assignment: extra fields in input"]
    R --> E["Uploads: dangerous files and names"]
    R --> F["Brute force: repeated guesses"]

Each branch has a built-in Laravel defense. The sections below cover them in turn.

CSRF: forged form submissions

In a cross-site request forgery attack, another website makes the victim's browser submit a request to yours, and the browser attaches the victim's session cookie. Laravel defends with a secret per-session token. Every state-changing form must include it:

PHP
<form method="POST" action="/profile">
    @csrf
    <input type="text" name="name">
</form>

@csrf renders a hidden _token field. The CSRF middleware rejects POST, PUT, PATCH and DELETE requests whose token does not match the session, with a 419 status. For JavaScript requests, send the token in an X-CSRF-TOKEN header (read it from a <meta name="csrf-token"> tag) or rely on the XSRF-TOKEN cookie that libraries such as Axios use automatically. See Forms, CSRF and Assets with Vite.

Never disable CSRF protection for browser routes to "fix" a failing form. Stateless token APIs (see Sanctum) do not use cookies for auth, so they are not exposed to CSRF in the same way.

XSS: escape output

Cross-site scripting happens when user-supplied text is printed as HTML and a script runs in other visitors' browsers. Blade's double-brace syntax escapes by default:

PHP
<p>{{ $comment->body }}</p>        {{-- safe: < becomes &lt; --}}
<p>{!! $comment->body !!}</p>      {{-- dangerous: printed raw --}}

Use {!! !!} only for HTML you generated and trust, never for user input. If you must allow some formatting (comments with bold text, say), convert with a Markdown renderer configured to escape or strip raw HTML, or sanitize with a dedicated library. Also remember other contexts: data placed in a JavaScript block should go through @json($value), and URLs from users should be checked so javascript: links are not allowed.

SQL injection: always bind

SQL injection happens when input becomes part of the SQL text. Eloquent and the query builder use PDO prepared statements, so values passed through them are safe:

PHP
User::where('email', $request->input('email'))->first();      // safe
DB::select('select * from users where email = ?', [$email]);  // safe: binding

The danger returns when you write raw SQL with concatenation:

PHP
DB::select("select * from users where email = '$email'");      // injectable
User::whereRaw("email = '$email'")->first();                    // injectable
User::orderBy($request->input('sort'));                         // column name from input

Bindings protect values, not identifiers. Column names, table names and sort directions cannot be bound, so check them against an allow-list:

PHP
$column = in_array($request->input('sort'), ['name', 'created_at'], true)
    ? $request->input('sort')
    : 'created_at';

User::orderBy($column)->get();

Mass assignment

Mass assignment is when you pass an entire request array into a model: User::create($request->all()). If the request includes is_admin=1 and that column is not protected, the attacker promotes themselves. Eloquent blocks this with $fillable (an allow-list) or $guarded (a deny-list):

PHP
class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
}

Even better, never pass raw request data. Use validated data, which contains only the fields you listed in your rules:

PHP
User::create($request->validated());

Avoid $guarded = [] outside of tightly controlled code, and never use $request->all() with create() or update().

Passwords, encryption and secrets

  • Passwords are hashed with Hash::make() (bcrypt by default; Argon2 is available) and checked with Hash::check(). Never store or log plain passwords, and let the hashed cast hash them on assignment.
  • Encryption for data you must read back later uses Crypt::encryptString($value) and decryptString(), or the encrypted model cast. Both depend on APP_KEY: keep it secret, never commit it, and understand that changing it makes old encrypted data and sessions unreadable.
  • Secrets such as API keys live in environment variables, not in code or git. See Configuration and Environments.

Rate limiting

Throttling slows brute-force and abuse. The throttle middleware applies named limiters defined in a service provider:

PHP
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->input('email') . '|' . $request->ip());
});

Route::post('/login', LoginController::class)->middleware('throttle:login');

Too many attempts return a 429 response with a Retry-After header. Use keys that identify the actor (user id or IP), and give login, password reset, code-sending and expensive endpoints their own tight limits.

Security headers and cookies

Headers instruct the browser to be stricter. Typical ones are X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Strict-Transport-Security (when you serve HTTPS only) and a Content-Security-Policy that limits where scripts can load from. Add them in a small middleware or at your web server. For session cookies, set SESSION_SECURE_COOKIE=true in production so they travel only over HTTPS, and keep http_only enabled so JavaScript cannot read them. See Middleware.

File uploads

Treat every upload as hostile:

  • Validate type and size with rules such as file, mimes:jpg,png,pdf or image, and max:2048.
  • Never trust the client's file name. Let Laravel generate one: $request->file('avatar')->store('avatars') creates a random name, whereas getClientOriginalName() can contain path tricks.
  • Store outside the web root by default (the local disk). Only expose what must be public, through the public disk and storage:link.
  • Never execute uploaded files, and serve user uploads with a content type you control.
  • For private files, return downloads through a controller that checks authorization instead of linking to the file directly.

See File Uploads and the Storage System.

Bindings versus concatenation, live

This example uses PDO with SQLite to show exactly what goes wrong with concatenation and why bindings stop it. This is plain PDO, which is what Laravel's database layer uses underneath.

PHP SQL injection versus bound parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unsafe query returns every user because the quote in the input ended the string and OR '1'='1' is always true. The bound query treats the whole attack string as an email address and finds nothing. The allow-list rejects the second sort value and falls back to id.

A CSRF-style token check

Laravel's CSRF defense boils down to this: generate an unguessable token, store it in the session, require it with each state-changing request and compare in constant time. This stand-in shows the logic. Laravel's real middleware also handles headers, cookies and exclusions.

PHP How a CSRF token check works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A malicious site can make your browser send the request, but it cannot read your session or your form, so it cannot know the token.

Keep APP_DEBUG=false in production. Debug pages show environment details and stack traces, which can leak secrets. Also run composer audit regularly and update dependencies, since many real attacks use known flaws in old packages.

A short checklist

  • Every form has @csrf; no routes are excluded without a reason.
  • Output uses {{ }}; each {!! !!} is justified and reviewed.
  • No SQL string contains request input; sort columns come from an allow-list.
  • Models use $fillable; controllers use validated(), never all().
  • Login and reset endpoints are rate limited.
  • Uploads are validated, randomly named and stored privately by default.
  • APP_DEBUG=false, APP_KEY secret, HTTPS enforced, dependencies audited.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @csrf output in a Blade form?

    @csrf renders a hidden _token field. The CSRF middleware compares it with the session's token and returns 419 when it is missing or wrong.
  2. 2. Which Blade syntax prints a value without escaping it, and is therefore dangerous for user input?

    {!! !!} outputs raw HTML. {{ }} escapes special characters, so a script tag in the data is shown as text.
  3. 3. Which of these is vulnerable to SQL injection?

    whereRaw with the variable concatenated into the string puts input inside the SQL text. The other calls bind the values.
  4. 4. Why is User::create($request->all()) risky?

    all() includes every field the client sends. Use validated data and a $fillable allow-list so only expected columns can be set.

Summary

  • Laravel protects you by default: CSRF tokens, escaped Blade output, prepared statements, $fillable and hashed passwords. Do not switch those off.
  • Use {!! !!} and raw SQL only with trusted data; bind values and allow-list identifiers such as sort columns.
  • Mass assignment: use $fillable and validated(), never all().
  • Hash passwords, encrypt data you must read back, and keep APP_KEY and API keys secret.
  • Rate limit sensitive endpoints, add security headers and use secure cookies.
  • Validate uploads, let Laravel generate file names and keep private files off the public disk.

Next: Logging, Exceptions and Error Handling