Spatie Laravel Prefixed IDs

repository·main·Indexed 41 days ago

https://github.com/spatie/laravel-prefixed-ids

A Laravel package for generating and managing friendly, prefixed IDs for Eloquent models, similar to Stripe. It provides the HasPrefixedId trait for models and the PrefixedIds class to resolve model instances across different types using their prefixes.

Tokens
2K
Snippets
13
Records
13
Agent score
2%

What's inside laravel-prefixed-ids

  1. Publish the prefixed-ids configuration

    main

    To customize the attribute name used to store prefixed IDs, publish the configuration file using the following Artisan command:

    php artisan vendor:publish --provider="Spatie\PrefixedIds\PrefixedIdsServiceProvider" --tag="prefixed-ids-config"
  2. Register models with prefixes

    main

    You must register your models and their corresponding prefixes with the PrefixedIds::registerModels method. This is typically done within a Service Provider. The keys in the array are the prefixes (including the trailing underscore) and the values are the model class names.

    Spatie\PrefixedIds\PrefixedIds::registerModels([
        'your_prefix_' => YourModel::class,
        'another_prefix' => AnotherModel::class,
    ]);
  3. Prepare the database for prefixed IDs

    main

    Each model using prefixed IDs requires a prefixed_id column in its database table. This column should be a string, nullable, and unique.

    If you want to use an attribute name other than prefixed_id, you must publish the config file and update the prefixed_id_attribute_name value.

    Schema::create('your_models_table', function (Blueprint $table) {
       $table->string('prefixed_id')->nullable()->unique();
    });
  4. Set up models for prefixed IDs

    main

    To enable prefixed IDs on an Eloquent model, use the Spatie\PrefixedIds\Models\Concerns\HasPrefixedId trait within your model class.

    namespace App\Models;
    
    use Illuminate\\]Database\Eloquent\Model;
    use Spatie\PrefixedIds\Models\Concerns\HasPrefixedId;
    
    class YourModel extends Model
    {
        use HasPrefixedId;
    }
  5. Use prefixed IDs in Laravel Route Model Binding

    main

    To allow Laravel to use the prefixed_id attribute for route model binding, override the getRouteKeyName method in your model to return the name of the attribute holding the prefixed ID.

    public function getRouteKeyName()
    {
        return 'prefixed_id';
    }
    
    // Example route usage:
    // Route::get('/api/your-models/{yourModel}', YourModelController::class)
    // URL: /api/your-models/your_model_fekjlmsme39dmMS
  6. Customize the unique ID generation logic

    main

    By default, the package uses Str::uuid() to generate the unique part of the ID. You can override this behavior by passing a custom callback to Spatie\PrefixedIds\PrefixedIds::generateUniqueIdUsing().

    // generate a unique Id with a set length
    Spatie\PrefixedIds\PrefixedIds::generateUniqueIdUsing(function(){
        $length = 8;
        return substr(md5(uniqid(mt_rand(), true)), 0, $length);
    });
  7. Find models across different types using PrefixedIds::find

    main

    The Spatie\PrefixedIds\PrefixedIds class provides static methods to automatically determine the correct model class based on the prefix of a given ID:

    • find($id): Returns the correct model instance or null.
    • findOrFail($id): Returns the correct model instance or throws NoPrefixedModelFound.
    • getModelClass($id): Returns the class name of the model or null.
    $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
    
    $class = Spatie\PrefixedIds\PrefixedIds::getModelClass('user_fj39fj3lsmxlsl'); // returns the right model class or null
  8. Find a specific model by its prefixed ID

    main

    Once a model is using the HasPrefixedId trait, you can retrieve it using its prefixed ID via the following methods on the model class:

    • findByPrefixedId($id): Returns the model instance or null if not found.
    • findByPrefixedIdOrFail($id): Returns the model instance or throws a NoPrefixedModelFound exception.
    YourModel::findByPrefixedId('your_model_fekjlmsme39dmMS'); // returns an instance of YourModel
    YourModel::findByPrefixedId('non-existing-id'); // returns null
    YourModel::findByPrefixedIdOrFail('non-existing-id'); // throws NoPrefixedModelFound
  9. Find a model using a prefixed ID

    main

    Once models are registered, you can use PrefixedIds::find() to resolve a model instance from a string containing a prefix and an ID. If no model matches the prefix, it returns null.

    use Spatie\PrefixedIds\PrefixedIds;
    
    $model = PrefixedIds::find('usr_12345');
    
    if ($model) {
        // Found the model
    }
  10. Register models with PrefixedIds

    main

    To enable the package to resolve models from prefixed IDs, you must register your models with their corresponding prefixes using the PrefixedIds class. You can register multiple models at once using registerModels() or a single model using registerModel().

    use Spatie\PrefixedIds\PrefixedIds;
    use App\Models\User;
    use App\Models\Post;
    
    // Register multiple models
    PrefixedIds::registerModels([
        'usr_' => User::class,
        'pst_' => Post::class,
    ]);
    
    // Or register a single model
    PrefixedIds::registerModel('usr_', User::class);