We’ve released a new package called spatie/laravel-prefixed-ids. In this post, I’d like to tell you all about it.

Why prefix ids

When thinking of companies with excellent APIs, Stripe is one of the first that comes to mind. They have excellent docs, and it seems like they have polished every detail to make sure the developer experience is just right.

One of the details they took care of is prefixing all of their ids. Here’s an example: when creating a token to interact with their API, you’ll notice that that token is prefixed. Let’s take a look at such a token:

sk_test_FKdleMEKfiemsiDSMEODL

In the example above, the sk stands for “secret key”, and test signifies that this token is meant to be used in Stripe’s test environment. Without that prefix, the value would just be a random string of which you’d have to guess what it is.

In fact, Stripe prefixes almost all of their ids. In my mind, this is a great little detail.

Prefixing ids in a Laravel app

The spatie/laravel-prefixed-ids can automatically generate prefixed ids in a Laravel app. It offers handy methods to retrieve Eloquent models using those prefixed ids.

You can install the package via Composer. No surprises there.

composer require spatie/laravel-prefixed-ids

On each model that needs a prefixed id, you should use the SpatiePrefixedIdsModelsConcernsHasPrefixedId trait.

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span><span class="hljs-title">Models</span>;
<p><span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span><span class="hljs-title">Database<span class="hljs-title">Eloquent<span class="hljs-title">Model;
<span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span><span class="hljs-title">PrefixedIds<span class="hljs-title">Models<span class="hljs-title">Concerns<span class="hljs-title">HasPrefixedId;</p>
<p><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">YourModel</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
<span class="hljs-keyword">use</span> <span class="hljs-title">HasPrefixedId</span>;
}
</p>

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.

Schema::create(<span class="hljs-string">'your_models_table'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(Blueprint $table)</span> </span>{
$table->string(<span class="hljs-string">'prefixed_id'</span>)->index();
});

To register your models, you should pass the desired prefix and your model’s class name to PrefixedIds::registerModels.

SpatiePrefixedIdsPrefixedIds::registerModels([
<span class="hljs-string">'your_prefix_'</span> => YourModel::class,
<span class="hljs-string">'another_prefix'</span> => AnotherModel::class,
]);

Typically, you would put the code above in a service provider.

With this in place, when a model is created, it will automatically have a unique, prefixed id in the prefixed_id attribute.

$model = YourModel::create();
$model->prefixed_id <span class="hljs-comment">// returns a random id like <code>your_model_fekjlmsme39dmMS

You can find the model with a given prefix by calling findByPrefixedId on it.

YourModel::findByPrefixedId(<span class="hljs-string">'your_model_fekjlmsme39dmMS'</span>); <span class="hljs-comment">// returns an instance of <code>YourModel
YourModel::findByPrefixedId('non-existing-id'); // returns null

You can call find on SpatiePrefixedIdsPrefixedIds to automatically get the right model for any given prefixed id.

$yourModel = SpatiePrefixedIdsPrefixedIds::find(<span class="hljs-string">'your_model_fekjlmsme39dmMS'</span>); <span class="hljs-comment">// returns an instance of <code>YourModel or null
$otherModel = SpatiePrefixedIdsPrefixedIds::find('other_model_3Fjmmfsmls'); // returns an instance of OtherModel or null

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.

<span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getRouteKeyName</span><span class="hljs-params">()</span>
</span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">'prefixed_id'</span>;
}

With this in place a route defined as…

Route::get(<span class="hljs-string">'your-model/{yourModel}'</span>, YourModelController::class)`

… can be invoked with an URL like “/your-model/your_model_fekjlmsme39dmMS”.

You’ll find more info on route model binding in the Laravel docs.

In closing

When creating an API, consider using prefixed ids. The consumers of your API will probably much appreciate this.

spatie/laravel-prefixed-ids isn’t the first package our team has created. Be sure to take a look at this list of PHP and Laravel packages our team has created previously.

Categories: PHP