Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/spatie/laravel-prefixed-ids
Friendly prefixed IDs for Laravel models
https://github.com/spatie/laravel-prefixed-ids
api dx eloquent laravel
Last synced: 4 days ago
JSON representation
Friendly prefixed IDs for Laravel models
- Host: GitHub
- URL: https://github.com/spatie/laravel-prefixed-ids
- Owner: spatie
- License: mit
- Created: 2021-02-24T09:49:08.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-03-06T16:04:58.000Z (8 months ago)
- Last Synced: 2024-09-20T05:18:40.759Z (about 2 months ago)
- Topics: api, dx, eloquent, laravel
- Language: PHP
- Homepage: https://spatie.be/open-source
- Size: 67.4 KB
- Stars: 162
- Watchers: 3
- Forks: 9
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Funding: .github/FUNDING.yml
- License: LICENSE.md
Awesome Lists containing this project
README
# Friendly prefixed IDs for Laravel models
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-prefixed-ids.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-prefixed-ids)
[![run-tests](https://github.com/spatie/laravel-prefixed-ids/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/laravel-prefixed-ids/actions/workflows/run-tests.yml)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-prefixed-ids.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-prefixed-ids)Prefixing an id will help users to recognize what kind of id it is. Stripe does this by default: customer ids are prefixed with `cus`, secret keys in production are prefixed with `sk_live_`, secret keys of a testing environment with `sk_test_` [and so on...](https://gist.github.com/fnky/76f533366f75cf75802c8052b577e2a5).
This package can generate such friendly prefixed ids for Eloquent models. Here's how such generated ids could look like.
```
user_fj39fj3lsmxlsl
test_token_dvklms109dls
```The package can retrieve the model for a given prefixed id.
```php
// on a specific model
User::findByPrefixedId('user_fj39fj3lsmxlsl'); // returns a User model or `null`
User::findByPrefixedIdOrFail('user_fj39fj3lsmxlsl'); // returns a User model or throws `NoPrefixedModelFound`// automatically determine the model of a given prefixed id
$user = PrefixedIds::getModelClass('user_fj39fj3lsmxlsl') // returns the right model for the id or `null`;
```## Support us
[](https://spatie.be/github-ad-click/laravel-prefixed-ids)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Installation
You can install the package via composer:
```bash
composer require spatie/laravel-prefixed-ids
```### Preparing your models
On each model that needs a prefixed id, you should use the `Spatie\PrefixedIds\Models\Concerns\HasPrefixedId` trait.
```php
namespace App\Models;use Illuminate\Database\Eloquent\Model;
use Spatie\PrefixedIds\Models\Concerns\HasPrefixedId;class YourModel extends Model
{
use HasPrefixedId;
}
```### Preparing the database
For each model that needs a prefixed id, you'll need to write a migration to add a `prefixed_id` column to its underlying table.
If you wish to use another attribute name, you should publish the config file (see below) and set the `prefixed_id_attribute_name` config value to the attribute name of your liking.
```php
Schema::create('your_models_table', function (Blueprint $table) {
$table->string('prefixed_id')->nullable()->unique();
});
```### Registering models with prefixed ids
To register your models, you should pass the desired prefix and the class name of your model to `PrefixedIds::registerModels`.
```php
Spatie\PrefixedIds\PrefixedIds::registerModels([
'your_prefix_' => YourModel::class,
'another_prefix' => AnotherModel::class,
]);
```Typically, you would put the code above in a service provider.
### Publish the config file
Optionally, You can publish the config file with:
```bash
php artisan vendor:publish --provider="Spatie\PrefixedIds\PrefixedIdsServiceProvider" --tag="prefixed-ids-config"
```This is the contents of the published config file:
```php
return [
/*
* The attribute name used to store prefixed ids on a model
*/
'prefixed_id_attribute_name' => 'prefixed_id',
];
```## Usage
When a model is created, it will automatically have a unique, prefixed id in the `prefixed_id` attribute.
```php
$model = YourModel::create();
$model->prefixed_id // returns a random id like `your_model_fekjlmsme39dmMS`
```### Finding a specific model
You can find the model with a given prefix by calling `findByPrefixedId` on it.
```php
YourModel::findByPrefixedId('your_model_fekjlmsme39dmMS'); // returns an instance of `YourModel`
YourModel::findByPrefixedId('non-existing-id'); // returns null
YourModel::findByPrefixedIdOrFail('non-existing-id'); // throws `NoPrefixedModelFound`
```### Finding across models
You can call `find` on `Spatie\PrefixedIds\PrefixedIds` to automatically get the right model for any given prefixed id.
```php
$yourModel = Spatie\PrefixedIds\PrefixedIds::find('your_model_fekjlmsme39dmMS'); // returns an instance of `YourModel` or `null`
$otherModel = Spatie\PrefixedIds\PrefixedIds::find('other_model_3Fjmmfsmls'); // returns an instance of `OtherModel` or `null`
$otherModel = Spatie\PrefixedIds\PrefixedIds::findOrFail('other_model_3Fjmmfsmls'); // returns an instance of `OtherModel` or throws `NoPrefixedModelFound`
```### Customizing the unique ID generated
You can use the function `Spatie\PrefixedIds\PrefixedIds::generateUniqueIdUsing()` to pass in a function to generate the unique ID. By default the library will use `Str::uuid()` to generate the ID.
```php
// generate a unique Id with a set length
Spatie\PrefixedIds\PrefixedIds::generateUniqueIdUsing(function(){
$length = 8;
return substr(md5(uniqid(mt_rand(), true)), 0, $length);
});
```## Using the prefixed ids in your routes
To use the prefixed ids in your routes, you'll have to add the `getRouteKeyName` method to your model. It should return the name of the attribute that holds the prefixed id.
```php
public function getRouteKeyName()
{
return 'prefixed_id';
}
```With this in place a route defined as...
```php
Route::get('/api/your-models/{yourModel}', YourModelController::class)`
```... can be invoked with an URL like `/api/your-models/your_model_fekjlmsme39dmMS`.
You'll find more info on route model binding in [the Laravel docs](https://laravel.com/docs/master/routing#route-model-binding).
## Testing
```bash
composer test
```## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributing
Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.
## Security Vulnerabilities
Please review [our security policy](../../security/policy) on how to report security vulnerabilities.
## Credits
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)This package is inspired by [excid3/prefixed_ids](https://github.com/excid3/prefixed_ids)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.