PHPackages                             spatie/laravel-prefixed-ids - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. spatie/laravel-prefixed-ids

ActiveLibrary[Database &amp; ORM](/categories/database)

spatie/laravel-prefixed-ids
===========================

Friendly prefixed IDs for Laravel models

1.5.0(4mo ago)175211.3k↓41.1%91MITPHPPHP ^8.2CI passing

Since Feb 24Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/spatie/laravel-prefixed-ids)[ Packagist](https://packagist.org/packages/spatie/laravel-prefixed-ids)[ Docs](https://github.com/spatie/laravel-prefixed-ids)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-laravel-prefixed-ids/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (5)Versions (13)Used By (1)

Friendly prefixed IDs for Laravel models
========================================

[](#friendly-prefixed-ids-for-laravel-models)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9b5d8bedbee4c8fb727dc9ca1dd44cca99f57370ec431a3531d3e52ac19c14c2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d70726566697865642d6964732e7376673f7374796c653d666c61742d737175617265)](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://camo.githubusercontent.com/89e3b5b27ffdda4346e30f6a2d0236d149c8df787a6883faa6815dfaeb9dc0e5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d70726566697865642d6964732e7376673f7374796c653d666c61742d737175617265)](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.

```
// 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
----------

[](#support-us)

[![](https://camo.githubusercontent.com/ab0141ae84fda8706ecd7f5291af0e2c7b1dd09be11d49ce5b72bab3947e8776/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d70726566697865642d6964732e6a70673f743d31)](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
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-prefixed-ids
```

### Preparing your models

[](#preparing-your-models)

On each model that needs a prefixed id, you should use the `Spatie\PrefixedIds\Models\Concerns\HasPrefixedId` trait.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\PrefixedIds\Models\Concerns\HasPrefixedId;

class YourModel extends Model
{
    use HasPrefixedId;
}
```

### Preparing the database

[](#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.

```
Schema::create('your_models_table', function (Blueprint $table) {
   $table->string('prefixed_id')->nullable()->unique();
});
```

### Registering models with prefixed ids

[](#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

[](#publish-the-config-file)

Optionally, You can publish the config file with:

```
php artisan vendor:publish --provider="Spatie\PrefixedIds\PrefixedIdsServiceProvider" --tag="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
-----

[](#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

[](#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
YourModel::findByPrefixedIdOrFail('non-existing-id'); // throws `NoPrefixedModelFound`
```

### Finding across models

[](#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`
$otherModel = Spatie\PrefixedIds\PrefixedIds::findOrFail('other_model_3Fjmmfsmls'); // returns an instance of `OtherModel` or throws `NoPrefixedModelFound`
```

### Customizing the unique ID generated

[](#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.

```
// 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
-------------------------------------

[](#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.

```
public function getRouteKeyName()
{
    return 'prefixed_id';
}
```

With this in place a route defined as...

```
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
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#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
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

59

—

FairBetter than 98% of packages

Maintenance76

Regular maintenance activity

Popularity51

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 68.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~182 days

Recently: every ~358 days

Total

11

Last Release

130d ago

Major Versions

0.0.1 → 1.0.02021-02-24

PHP version history (2 changes)0.0.1PHP ^8.0

1.4.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (69 commits)")[![francoism90](https://avatars.githubusercontent.com/u/5028905?v=4)](https://github.com/francoism90 "francoism90 (9 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (8 commits)")[![whobutsb](https://avatars.githubusercontent.com/u/868190?v=4)](https://github.com/whobutsb "whobutsb (6 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (4 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (2 commits)")[![masterix21](https://avatars.githubusercontent.com/u/6555012?v=4)](https://github.com/masterix21 "masterix21 (1 commits)")

---

Tags

apidxeloquentlaravelspatielaravel-prefixed-ids

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-laravel-prefixed-ids/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-prefixed-ids/health.svg)](https://phpackages.com/packages/spatie-laravel-prefixed-ids)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k102.4M1.4k](/packages/spatie-laravel-permission)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[spatie/laravel-backup

A Laravel package to backup your application

6.0k24.4M244](/packages/spatie-laravel-backup)[spatie/laravel-passkeys

Use passkeys in your Laravel app

471890.7k39](/packages/spatie-laravel-passkeys)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M165](/packages/spatie-laravel-health)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

213421.0k2](/packages/wnx-laravel-backup-restore)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
