Secure your primary id in your Laravel Project
Laravel often have easy way to resolve the Models from route bindings that are often shared as your primary id.
Ever wondered, if you don't want to expose the primary index of your entities to end-users in your route URL or response JSON, this package provides an amazing out-of-the-box solution with the help of HashId's package.
# Example
Your API or WEB url that often you shared let's say for User whose id
is 1
would be
https://{host}/api/users/1
or
https://{host}/users/1/update
2
3
4
5
With this package the id
would be updated to
https://{host}/api/users/aE41jhk41
or
https://{host}/users/aE41jhk41/update
2
3
4
5
Here aE41jhk41
is a hash generated for id 1
.
# How it works
- Secure Ids package makes use of Laravel-Hashids (opens new window) for generating the secure hashes for your models
- It identifies all your Model classes that would be present either within
app
orapp/Models
directory or you can specify the directory - For each model class it maintains a unique connection for generation of the id, this way the hash for
1
would be different forApp\Models\User
and similary hash for1
inApp\Models\Role
would be totally different. - Additionally, it generates a unique salt with the help of
app.key
so as to keep generation of hash, unique for each project.
# How to use
# Installation
Install this package in your project with composer
composer require saiashirwadinformatia/secure-ids
Publish the config file used by this package
php artisan vendor:publish --provider="SaiAshirwadInformatia\SecureIds\SecureIdsServiceProvider"
Update the config file as required, often it auto identifies the basic structure of Laravel, change if you are using a separate structure.
return [
'models_directory' => 'Models',
'model_namespace' => 'App\\Models\\',
'length' => 13,
];
2
3
4
5
# Usage
Load the configs of SecureIds by calling in your AppServiceProvider boot method
use SaiAshirwadInformatia\SecureIds\Facades\SecureIds;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
SecureIds::load();
}
2
3
4
5
6
7
8
9
10
11
12
13
Use trait HasSecureIds
for the models you want to enable securing the id.
use SaiAshirwadInformatia\SecureIds\Models\Traits\HasSecureIds;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
// Add below Trait to enable securing id's
use HasSecureIds;
// ...
2
3
4
5
6
7
8
That's it done!
# What it does
- With the above configuration you have enabled JSON response for API to include
id
with theHashId
- If it's not API, the property to reference
HashId
is available as$user->secure_id
- Ensure when passing in URL
secure_id
is passed so it auto-resolves the bindings
More Examples coming soon!
# Read More
https://packagist.org/packages/saiashirwadinformatia/secure-ids (opens new window)
Share your feedback or suggestions!