Spatie released a new package called spatie/laravel-prefixed-ids.
A Laravel Friendly prefixed IDs Package for Laravel.
This package can generate such friendly prefixed ids for Eloquent models. As Freek Van der Herten describes in his introductory post about this package, it provides human-readable prefixes to otherwise random IDs. For example, you might give a token ID that contains a friendly prefix:
token_sandbox_FKdleMEKfiemsiDSMEODL
The token_sandbox
prefix could indicate that it’s a token for your sandbox environment, which would otherwise look like a random ID.
⚡ Installation
composer require spatie/laravel-prefixed-ids
Here’s an example model from Freek’s article that illustrates how you use this package to indicate the model has a prefixed column:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\PrefixedIds\Models\Concerns\HasPrefixedId;
class YourModel extends Model
{
use HasPrefixedId;
}
If you follow the above installation instructions, you’ll need a table column for your model that contains the prefixed id, which defaults to prefixed_id
.
✏ 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
.
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:
php artisan vendor:publish --provider="Spatie\PrefixedIds\PrefixedIdsServiceProvider" --tag="laravel-prefixed-ids-config"
This is the contents of the published config file:
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.
$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.
YourModel::findByPrefixedId('your_model_fekjlmsme39dmMS'); // returns an instance of `YourModel`
YourModel::findByPrefixedId('non-existing-id'); // returns null
Finding across models
You can call find
on Spatie\PrefixedIds\PrefixedIds
to automatically get the right model for any given prefixed id.
$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`