Friendly Prefix IDs for Eloquent Models

Packages

March 9th, 2021

spatie-friendly-prefixed-ids.png

Laravel Prefixed IDs is a package by Spatie that automatically adds a friendly prefixed ID to Laravel 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.

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 installation instructions, you'll need a table column for your model that contains the prefixed id, which defaults to prefixed_id.

Here are a few examples of how you might use this package with a model containing a prefixed ID:

$model = ApiToken::create();
$model->prefixed_id

ApiToken::findByPrefixedId('token_sandbox_fekjlmsme39dmMS'); // returns model
ApiToken::findByPrefixedId('invalid-id'); // null

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.