---
name: laravel-security-review
description: Review Laravel and PHP code for security defects before it ships. Use when reviewing a diff, a pull request, or a controller, model, route, migration, or Blade template, and whenever the user asks about Laravel security, mass assignment, SQL injection, IDOR, authorization gaps, or unsafe file uploads.
title: laravel-security-review
canonical_url: https://skilld.dev/gh/catidegla/skillbelt/laravel-security-review
last_updated: 2026-09-22T17:38:46.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/patterns.md](https://skilld.dev/api/skills-raw/catidegla/skillbelt/laravel-security-review/references/patterns.md).
>
> If the user asked to install this Skill, run `npx skilld install catidegla/skillbelt/laravel-security-review`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/laravel-security-review`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/catidegla/skillbelt/laravel-security-review) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/laravel-security-review`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/laravel-security-review --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/laravel-security-review --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Laravel security review

Find the defects that actually reach production in Laravel apps. Framework defaults handle a lot, so the real bugs cluster where a developer stepped outside them: a raw query, a manual `find()` without an authorization check, a `{!! !!}` in a Blade template.

## How to run a review

1. **Scope it.** Prefer the diff over the whole app. `git diff main...HEAD -- '*.php' '*.blade.php'`. Reviewing everything produces noise and misses the change that introduced the bug.
2. **Grep for the high-signal patterns below.** Each one is a place the framework stops protecting you.
3. **Verify before reporting.** Read enough surrounding code to confirm the input is attacker-controlled and reaches the sink. A `whereRaw` with a hardcoded string is not an injection.
4. **Report with a concrete failure path.** "User A sends `?user_id=2` and reads User B's invoice" beats "possible IDOR".

Rank findings by exploitability, not by category. One confirmed authorization gap matters more than ten hardened-header suggestions.

## The patterns that matter

### Authorization gaps

The single most common real vulnerability in Laravel apps. Authentication is usually correct because middleware handles it. Authorization is per-action and gets forgotten.

```php
// Vulnerable: any authenticated user can read any invoice.
public function show($id)
{
    return view('invoices.show', ['invoice' => Invoice::findOrFail($id)]);
}

// Fixed: the policy runs before the record is returned.
public function show(Invoice $invoice)
{
    $this->authorize('view', $invoice);

    return view('invoices.show', ['invoice' => $invoice]);
}
```

Check for:
- Controller actions that load a model by id from the request without a matching `authorize`, `can`, or policy call.
- Route model binding that is scoped globally rather than to the current user. `Route::get('/invoices/{invoice}')` binds any invoice, not just the caller's.
- `Gate::allows` results that are computed and then ignored.
- Policies registered but never invoked, which looks safe in review and is not.

Nested resources deserve extra attention. `/projects/{project}/tasks/{task}` must verify that `$task` actually belongs to `$project`, or an attacker swaps one id and walks the whole table. Use `->scopeBindings()` or check the relationship explicitly.

### Mass assignment

```php
// Vulnerable: $guarded = [] plus a request body containing is_admin=1.
class User extends Model
{
    protected $guarded = [];
}

$user->update($request->all());
```

`$guarded = []` disables protection entirely. It is common in seeders and then copied into real models. Prefer an explicit `$fillable`, and pass `$request->validated()` rather than `$request->all()`, so the form request defines the allowed keys in one place.

Watch for `forceFill`, which bypasses both `$fillable` and `$guarded`.

### SQL injection

Eloquent and the query builder parameterize automatically. Injection appears where a developer opts out:

```php
// Vulnerable: interpolated into raw SQL.
DB::select("SELECT * FROM users WHERE email = '{$request->email}'");
User::whereRaw("name LIKE '%{$request->q}%'")->get();

// Fixed: bindings.
DB::select('SELECT * FROM users WHERE email = ?', [$request->email]);
User::whereRaw('name LIKE ?', ["%{$request->q}%"])->get();
```

Grep targets: `DB::raw`, `whereRaw`, `havingRaw`, `orderByRaw`, `selectRaw`, `DB::statement`, `DB::unprepared`.

`orderByRaw` deserves its own pass. Column names and sort directions cannot be bound as parameters, so developers interpolate them. Validate against an allowlist:

```php
$sortable = ['created_at', 'total', 'name'];
abort_unless(in_array($request->sort, $sortable, true), 400);
$direction = $request->direction === 'desc' ? 'desc' : 'asc';

Order::orderBy($request->sort, $direction)->get();
```

### Blade and XSS

`{{ }}` escapes. `{!! !!}` does not.

```blade
{{-- Vulnerable when $post->body contains user input --}}
<div>{!! $post->body !!}</div>
```

Every `{!! !!}` needs a reason. If it renders user-supplied HTML, it needs sanitizing first with a real HTML sanitizer, not a regex. Also check `@json` and `Js::from` when injecting data into inline scripts, and any attribute built by string concatenation, since escaping rules inside a `<script>` block or an `href` differ from body text.

### Command injection

```php
// Vulnerable
exec("convert {$request->file} output.png");

// Fixed: no shell, arguments passed as an array.
use Symfony\Component\Process\Process;

$process = new Process(['convert', $path, 'output.png']);
$process->run();
```

Grep targets: `exec`, `shell_exec`, `system`, `passthru`, `proc_open`, `popen`, and backticks. `escapeshellarg` is a fallback, not a fix, and it is easy to misuse when the value lands inside a quoted string.

### File uploads

```php
// Vulnerable: trusts the client-supplied MIME type and original name.
$request->file('avatar')->storeAs('public', $request->file('avatar')->getClientOriginalName());

// Fixed: validate real content, let the framework generate the name.
$request->validate([
    'avatar' => ['required', 'file', 'mimes:jpg,png,webp', 'max:2048'],
]);

$path = $request->file('avatar')->store('avatars', 'public');
```

`mimes` checks actual file content. `mimetypes` trusts the request header. Never reuse `getClientOriginalName`, which carries traversal sequences and double extensions. Store uploads outside the web root, or in a disk that does not execute PHP.

### Unsafe deserialization

`unserialize()` on request data is remote code execution when a gadget chain exists in the dependency tree, and Laravel apps have large dependency trees. Use `json_decode`. If you must unserialize, pass `['allowed_classes' => false]`.

Also check `Crypt::decrypt` on attacker-supplied strings and any signed-URL handling that skips signature verification.

### Secrets and configuration

- `APP_DEBUG=true` in production leaks environment variables, database credentials and full stack traces through the Ignition error page. Confirm `APP_ENV` and `APP_DEBUG` for the deployed environment, not just `.env.example`.
- API keys, tokens and passwords committed in config files or migrations. `config/services.php` should read `env()`, and `env()` should only ever be called inside `config/`, because `config:cache` makes `env()` return null everywhere else.
- `.env` reachable over HTTP because the document root points at the project root instead of `public/`.

### Authentication details

- `Hash::check` for passwords, never `==` or `===`. For non-password token comparison use `hash_equals`.
- Password reset and email verification links that do not expire or are not single use.
- Rate limiting on login, password reset and any endpoint that sends mail or SMS. `throttle` middleware or a `RateLimiter` definition.
- Session fixation: Laravel regenerates on login through the starter kits, but hand-rolled login flows often skip `$request->session()->regenerate()`.

### CSRF

`VerifyCsrfToken` covers session-authenticated routes. Look for:
- Routes added to the `$except` array, which is occasionally correct for webhooks and usually not.
- Webhook endpoints that skip CSRF and then also skip signature verification, which is the actual bug.
- State-changing actions served over `GET`.

### Mail and SSRF

- User-controlled URLs passed to `Http::get` without an allowlist reach internal metadata endpoints and localhost services.
- Redirects built from `$request->input('next')`. Validate against known paths or use `URL::signedRoute`.

## Reference

`references/patterns.md` holds the grep commands for each pattern above, ready to run against a working tree.

## Reporting

For each finding give:

- **File and line.**
- **What an attacker sends** and what they get back.
- **The fix**, as a diff where it is short enough.
- **Severity**, judged by what the attacker actually gains.

State clearly when something is a hardening suggestion rather than a live defect. Mixing the two trains people to ignore the whole report.
