PHPackages                             imran/laravel-encrypted-route-params - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. imran/laravel-encrypted-route-params

ActiveLibrary[Security](/categories/security)

imran/laravel-encrypted-route-params
====================================

Encrypt sensitive Laravel route parameters with Crypt and decrypt them before implicit binding.

0.0.4(1mo ago)011MITPHPPHP ^8.1

Since May 15Pushed 1mo agoCompare

[ Source](https://github.com/grim-reapper/laravel-encrypted-route-params)[ Packagist](https://packagist.org/packages/imran/laravel-encrypted-route-params)[ Docs](https://github.com/grim-reapper/laravel-encrypted-route-params)[ RSS](/packages/imran-laravel-encrypted-route-params/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (14)Versions (5)Used By (0)

Laravel Encrypted Route Params
==============================

[](#laravel-encrypted-route-params)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4f62d133f036532fa3cb1cdcf4c50f8f24cb1b677834895beb0fa2f818baeff9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696d72616e2f6c61726176656c2d656e637279707465642d726f7574652d706172616d732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/imran/laravel-encrypted-route-params)[![Total Downloads](https://camo.githubusercontent.com/494bf33adc8fc8eeb91985716d7ef6786fbc566beb198c073014c849393a07fa/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696d72616e2f6c61726176656c2d656e637279707465642d726f7574652d706172616d732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/imran/laravel-encrypted-route-params)[![License](https://camo.githubusercontent.com/59cc9d29554691225d2a86978a2a6d92f9d313fe8003a3de37190574f7f2da3c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f696d72616e2f6c61726176656c2d656e637279707465642d726f7574652d706172616d732e7376673f7374796c653d666c61742d737175617265)](https://github.com/grim-reapper/laravel-encrypted-route-params/blob/main/LICENSE)

🔒 Stop ID Scraping &amp; Leakage with Transparent URL Encryption
----------------------------------------------------------------

[](#-stop-id-scraping--leakage-with-transparent-url-encryption)

Are you still exposing raw database IDs in your URLs?

`https://your-app.com/invoices/1024`

### The Problem

[](#the-problem)

Exposing raw IDs is a major security and business intelligence risk:

1. **ID Scraping:** Competitors can easily guess next/previous IDs to scrape your data.
2. **Business Intelligence Leakage:** Anyone can see exactly how many orders, users, or invoices you have just by looking at the URL.
3. **Insecure Direct Object Reference (IDOR):** While middleware should prevent unauthorized access, raw IDs make it tempting for attackers to probe for weaknesses.
4. **Ugly URLs:** Raw IDs feel "naked" and less professional than modern, obfuscated identifiers.

### The Solution

[](#the-solution)

**Laravel Encrypted Route Params** provides a seamless, "drop-in" way to encrypt sensitive path parameters using Laravel’s native `Crypt` facade.

It handles everything automatically:

- **Transparent Encryption:** Use `route()` as normal; it encrypts the parameters on the fly.
- **Automatic Decryption:** Middleware decrypts values **before** implicit route model binding, so your controllers don't even know it happened.
- **Shorter Tokens:** Optional compact mode for cleaner, shorter URLs.
- **JSON Support:** Can also decrypt tokens inside JSON request payloads.
- **Model-Level Control:** Use a Trait to automatically encrypt IDs in all URLs and JSON resources.
- PHP `^8.1`
- Laravel `^10.0|^11.0|^12.0|^13.0`
- A valid `APP_KEY`

---

🚀 Installation
--------------

[](#-installation)

```
composer require imran/laravel-encrypted-route-params
```

The package is **auto-discovered**. If discovery is disabled, register the provider manually:

```
// config/app.php
'providers' => [
    // ...
    Imran\EncryptedRouteParams\EncryptedRouteParamsServiceProvider::class,
],
```

---

⚙️ Quick Start
--------------

[](#️-quick-start)

### 1. Middleware Setup (Required)

[](#1-middleware-setup-required)

Decryption must run **before** `SubstituteBindings`.

#### Laravel 11 / 12 / 13 (`bootstrap/app.php`)

[](#laravel-11--12--13-bootstrapappphp)

```
use Illuminate\Foundation\Configuration\Middleware;
use Imran\EncryptedRouteParams\Middleware\DecryptEncryptedRouteParameters;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(
            remove: [\Illuminate\Routing\Middleware\SubstituteBindings::class],
            append: [
                DecryptEncryptedRouteParameters::class,
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],
        );
    })
```

### 2. Usage on Routes

[](#2-usage-on-routes)

Just add `->encrypted()` to any route definition:

```
use Illuminate\Support\Facades\Route;

// Encrypt the {invoice} parameter automatically
Route::get('/invoices/{invoice}', [InvoiceController::class, 'show'])
    ->name('invoices.show')
    ->encrypted();
```

### 3. Generate URLs

[](#3-generate-urls)

Just use the standard `route()` helper! If `transparent_url_generation` is enabled (default), it just works:

```
// Generates: https://app.com/invoices/eyJpdiI6Il... (encrypted)
$url = route('invoices.show', ['invoice' => $invoice->id]);
```

---

🏛️ Model-Level Control (Automatic)
----------------------------------

[](#️-model-level-control-automatic)

Instead of marking every route, you can enable encryption directly on your Eloquent models. This is useful for sensitive IDs that should **always** be encrypted in URLs and JSON responses.

### 1. Add the Trait

[](#1-add-the-trait)

Add `HasEncryptedAttributes` to your model and define which attributes should be encrypted:

```
use Illuminate\Database\Eloquent\Model;
use Imran\EncryptedRouteParams\Traits\HasEncryptedAttributes;

class Invoice extends Model
{
    use HasEncryptedAttributes;

    /**
     * The attributes that should be encrypted in URLs and toArray().
     */
    protected $encrypted = [
        'id',
        'customer_id',
    ];
}
```

### 2. What this does:

[](#2-what-this-does)

- **Automatic URLs:** `route('invoices.show', $invoice)` will now automatically produce an encrypted URL, even if the route is NOT marked with `->encrypted()`.
- **Automatic JSON:** When you return the model from a controller, use it in a **JsonResource**, or call `$invoice->toArray()`, the listed attributes will be encrypted automatically.
- **Transparent Decryption:** The middleware automatically detects models using this trait and decrypts the route parameters before they reach your controller.

---

🛠️ Advanced Features
--------------------

[](#️-advanced-features)

### Selecting Specific Parameters

[](#selecting-specific-parameters)

```
// Only encrypt 'invoice', leave 'org' as plaintext
Route::get('/orgs/{org}/invoices/{invoice}', ...)
    ->encrypted(only: ['invoice']);

// Encrypt everything except the 'slug'
Route::get('/u/{user}/{slug}', ...)
    ->encrypted(except: ['slug']);
```

### Shorter Tokens (`cipher` = `compact`)

[](#shorter-tokens-cipher--compact)

Tired of long Base64 strings? Switch to compact mode in your `.env`:

```
ENCRYPTED_ROUTE_PARAMS_CIPHER=compact
```

This uses AES-256-GCM + HKDF to produce significantly shorter tokens while maintaining high security.

### JSON &amp; Form Request Support

[](#json--form-request-support)

Decrypt parameters sent in request bodies automatically by adding the middleware. Supported content types: `application/json`, `application/x-www-form-urlencoded`, and `multipart/form-data` (file uploads are left unchanged). You can use the provided alias `encrypted.json.request` (once configured in config):

```
Route::post('/api/invoices', ...)
    ->middleware([\Imran\EncryptedRouteParams\Middleware\DecryptEncryptedJsonRequestParameters::class]);
```

---

🧪 Helper Methods
----------------

[](#-helper-methods)

The package provides several global helper methods for manual encryption/decryption:

### `encrypt_route_param(mixed $value)`

[](#encrypt_route_parammixed-value)

Encrypt a scalar value using the package's configuration. Useful for manually building JSON responses or payloads.

```
return [
    'id' => encrypt_route_param($user->id),
];
```

### `decrypt_route_param(string $token)`

[](#decrypt_route_paramstring-token)

Decrypt a token produced by the package.

```
$rawId = decrypt_route_param($request->input('encrypted_id'));
```

### `encrypted_route(string $name, array $parameters = [], bool $absolute = true)`

[](#encrypted_routestring-name-array-parameters---bool-absolute--true)

Explicitly generate an encrypted route URL. This is useful if you have `transparent_url_generation` set to `false`.

```
$url = encrypted_route('users.show', ['user' => 1]);
```

---

📄 Configuration
---------------

[](#-configuration)

Publish the config file:

```
php artisan vendor:publish --tag=encrypted-route-params-config
```

### Options &amp; Environment Variables

[](#options--environment-variables)

KeyEnvironment VariableDefaultDescription`enabled``ENCRYPTED_ROUTE_PARAMS_ENABLED``true`Master switch for the package.`transparent_url_generation``ENCRYPTED_ROUTE_PARAMS_TRANSPARENT_URL``true`If true, wraps Laravel's `UrlGenerator` so `route()` works automatically.`cipher``ENCRYPTED_ROUTE_PARAMS_CIPHER``laravel``laravel` (standard) or `compact` (shorter tokens).`failure``ENCRYPTED_ROUTE_PARAMS_FAILURE``404`Returns `404` or `400` on decryption failure.`log_failures``ENCRYPTED_ROUTE_PARAMS_LOG_FAILURES``true`Log decryption failures to your application logs.`max_plaintext_length``ENCRYPTED_ROUTE_PARAMS_MAX_PLAINTEXT_LENGTH``4096`Max size of data before encryption.`decrypt_json_strategy``ENCRYPTED_ROUTE_PARAMS_JSON_STRATEGY``keys``keys` (explicit keys) or `all_strings` (recursive search).`decrypt_json_request_keys``ENCRYPTED_ROUTE_PARAMS_JSON_KEYS``''`Comma-separated list of keys to decrypt in JSON bodies.`json_decrypt_strict``ENCRYPTED_ROUTE_PARAMS_JSON_STRICT``false`If true, returns 400 on invalid JSON ciphertext.`middleware``ENCRYPTED_ROUTE_PARAMS_MIDDLEWARE``encrypted.route.params`Alias registered for route parameter decryption middleware.`json_middleware``ENCRYPTED_ROUTE_PARAMS_JSON_MIDDLEWARE``''`Optional alias for JSON request decryption middleware.---

❤️ Support the Project
----------------------

[](#️-support-the-project)

This package is free and open-source. If you find it useful, please consider:

- **Starring the repo** on GitHub.
- **Reporting bugs** or suggesting features via Issues.
- **Contributing code** via Pull Requests.

### 💖 Sponsors

[](#-sponsors)

If your company uses this package in production, please consider sponsoring development to ensure its long-term maintenance. Contact **** for sponsorship opportunities.

---

🤝 Contributing
--------------

[](#-contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

🔒 Security
----------

[](#-security)

If you discover any security-related issues, please email **** instead of using the issue tracker.

📜 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance92

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~10 days

Total

4

Last Release

39d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7252105628ffa6f064585370161626c7c72e68dd2e74ee66aa50d5894543c183?d=identicon)[webz2feel](/maintainers/webz2feel)

---

Top Contributors

[![grim-reapper](https://avatars.githubusercontent.com/u/7957389?v=4)](https://github.com/grim-reapper "grim-reapper (5 commits)")

---

Tags

laravelsecurityencryptionroutingobfuscationroute-parameters

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/imran-laravel-encrypted-route-params/health.svg)

```
[![Health](https://phpackages.com/badges/imran-laravel-encrypted-route-params/health.svg)](https://phpackages.com/packages/imran-laravel-encrypted-route-params)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77922.3M186](/packages/laravel-mcp)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M133](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k30.2M151](/packages/laravel-cashier)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M136](/packages/laravel-pulse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
