Automatic route key encryption for Laravel Eloquent using Hashids (short, unique, non-sequential IDs) with prefix support.
By default Laravel uses numeric, sequential IDs for models. These numeric IDs are then also used as route keys:
route('users.show', User::find(1)) // http://app.test/user/1
route('users.show', User::find(2)) // http://app.test/user/2
route('users.show', User::find(3)) // http://app.test/user/3
This package automatically encodes the model ID, so that sequence is not externally exposed:
route('users.show', User::find(1)) // http://app.test/user/m8y78
route('users.show', User::find(2)) // http://app.test/user/p8b7v
route('users.show', User::find(3)) // http://app.test/user/dvd6v
This is useful to hide sensitive app information (e.g. total number of users, invoices, etc).
You can install the package via composer:
composer require io238/eloquent-encoded-ids
In order to encode the ID of a Laravel model, simply add the HasEncodedIds
trait to the model:
namespace App\Models;
use Io238\EloquentEncodedIds\Traits\HasEncodedIds;
class User extends Model {
use HasEncodedIds;
// ..
}
Internally, Laravel will still use the numeric ID within controllers and also stores them as numeric IDs in the database:
class UserController extends Controller {
public function show(User $user)
{
return $user->id; // 1
}
}
By default this package adds a prefix to the encoded ID, which helps to identify what type of ID has been encoded.
Example: The User
model has encoded IDs starting with u_
, such as u_m8y78
.
It uses the model name's first letter, or you can explicitly provide a prefix as a protected property of the model:
class User extends Model {
use HasEncodedIds;
protected $prefix = 'usr';
}
This package works out-of-the-box. Nevertheless, you can publish and customize the config file with:
php artisan vendor:publish --provider="\Io238\EloquentEncodedIds\EncodedIdsProvider" --tag="config"
This is the contents of the default config file:
return [
// Minimum length of encoded IDs
'length' => 5,
// Alphabet to be used to generate encoded IDs
// By default this list excludes ambiguous characters
'alphabet' => '123456789abcdefghikmnpqrstuvwxyz',
// Ignore uppercase/lowercase for encoded IDs
'case-insensitive' => true,
// Encryption salt
// Warning: changing the salt, will produce different encoded IDs
'salt' => env('APP_KEY'),
// Use a prefix to the encoded ID, to be able to recognize the model that the ID belongs to
'prefix' => true,
// Character used to separate the prefix from the encoded ID
'separator' => '_',
];
composer test
Please see CONTRIBUTING for details.
Please review the security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.