Friendly prefixed IDs for Laravel models

Overview

Friendly prefixed IDs for Laravel models

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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

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

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

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. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

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.

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.

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.

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="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
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.

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

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.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

This package is inspired by excid3/prefixed_ids

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Laravel Ban simplify blocking and banning Eloquent models.
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

Add Social Reactions to Laravel Eloquent Models. It lets people express how they feel about the content. Fully customizable Weighted Reaction System & Reaction Type System with Like, Dislike and any other custom emotion types. Do you react?
The package lets you generate TypeScript interfaces from your Laravel models.

Laravel TypeScript The package lets you generate TypeScript interfaces from your Laravel models. Introduction Say you have a model which has several p

A Laravel package for multilingual models
A Laravel package for multilingual models

Introduction If you want to store translations of your models into the database, this package is for you. This is a Laravel package for translatable m

A Laravel package for attachment files to models

Laravel attachmentable package A package for attachment files to models Installation Run the command below to add this package: composer require larav

A package to implement repository pattern for laravel models

Laravel Model UUID A simple package to use Repository Pattern approach for laravel models . Repository pattern Repositories are classes or components

Advanced Laravel models filtering capabilities

Advanced Laravel models filtering capabilities Installation You can install the package via composer: composer require pricecurrent/laravel-eloquent-f

A Laravel package making a diagram of your models, relations and the ability to build them with it
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

A Laravel Code Generator based on your Models using Blade Template Engine
A Laravel Code Generator based on your Models using Blade Template Engine

Laravel Code Generator is a PHP Laravel Package that uses Blade template engine to generate code for you. The difference between other code generators

Comments
  • Add support for ordered UUID's

    Add support for ordered UUID's

    Added a little config option to use ordered UUID's instead of UUIDv4's. Added a link to an article about (security) differences/advantages in the README as well.

    -- This is a first for me, hope I'm doing things right! 😬

    opened by wouterdijkstra 3
  • Generate the unique IDs using a callable function

    Generate the unique IDs using a callable function

    Per my discussion - https://github.com/spatie/laravel-prefixed-ids/discussions/13

    I wanted the ability to customize the length of the unique IDs. @freekmurze mentioned that it would be better to create a static method that calls a function to generate the unique IDs.

    You can now now customize the generated ids by doing the following:

    PrefixedIds::generateUniqueIdUsing(function(){
        return rand();
    });
    

    This is completely optional, if the method is not used the library will continue using laravel's Str::uuid() method to generate the unique Ids.

    @freekmurze - In your example you had $model variable included in the function I'm not sure what you meant on how that would be used. Could you provide some more details on what you intended?

    Please let me know what can be improved. Once you're happy with the pull request changes I can update the readme with usage and example. Thank you for the consideration.

    opened by whobutsb 1
  • Add support for primary prefixed ids and stubs to accomodate for this

    Add support for primary prefixed ids and stubs to accomodate for this

    This PR adds support for Prefixed IDs being the primary IDs.

    Probably not perfect yet, but the start is there.

    Setting prefixed_id_is_primary to true sets $incrementing to false for all Models using the Spatie\PrefixedIds\Models\Concerns\HasPrefixedId trait.

    Added custom stubs for this as well. Publishing these will change the stubs to include the HasPrefixedId trait and update the migration to be $table->string('id)->primary();.

    Reflected this in the README as well.

    These stubs are publishable by running php artisan prefixedids:stubs.

    opened by wouterdijkstra 1
  • Should prefixed_id columns be unique instead?

    Should prefixed_id columns be unique instead?

    // README.md
    
    Schema::create('your_models_table', function (Blueprint $table) {
       $table->string('prefixed_id')->index();
    });
    

    As this package generates an uuid for each model shouldn't this be unique() instead of index()?

    opened by francoism90 1
Releases(1.3.0)
Owner
Spatie
We create open source, digital products and courses for the developer community
Spatie
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Λгi 25 Aug 31, 2022
Strongly typed settings for Laravel, includes built-in encryption and friendly validation.

Strongly Typed Laravel Settings Install composer require bogdankharchenko/typed-laravel-settings Model Setup namespace App\Models\User; use Illuminat

Bogdan Kharchenko 10 Aug 31, 2022
PHP implementation of Nanoid, secure URL-friendly unique ID generator

Nanoid-php A tiny (179 bytes), secure URL-friendly unique string ID generator for JavaScript Safe. It uses cryptographically strong random APIs and gu

__hidehalo 548 Jan 4, 2023
Create a downloads list - quick and easy. With categories and mobile friendly design

Simple downloads list plugin for wordpress Create a downloads list - quick and easy. With categories and mobile friendly design What is Simple downloa

Neofix 2 Dec 4, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023
Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Laravel-Mediable Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel. Features Filesystem-driven appro

Plank Design 654 Dec 30, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
Record the change log from models in Laravel

This package will help you understand changes in your Eloquent models, by providing information about possible discrepancies and anomalies that could

Owen IT Services 2.5k Dec 30, 2022
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 955 Dec 25, 2022