HasUuid

Automatically generate an ordered UUIDv4 for your Models

This is an alternative Trait. You can also use the HasUuids trait from Laravel which supports the UUID as a primary key.

If you don't want to expose your increment-id to the client side, then UUID would be a great candidate to be your secondary identifier.

Pros:

  • Not too ugly (in URL or request's payload)

  • People can't hijack the UUID

Requirement

Your table must add a unique uuid column in order to use this trait

$table->uuid()->unique();

Soft Deletes

If you also use softDeletes, then use this unique index instead:

$table->unique(['uuid', 'deleted_at']);

Usage

Simply use the trait

use SaasReady\Traits\HasUuid;

class User extends Model
{
    use HasUuid;
}

Model Route Binding

By default, when using HasUuid , the default key for model route binding will be pointed to uuid column.

If you wish to use another column, you can either:

  • Add the desired column in the route definition

    • Route::get('{user:slug}', ...);

  • Override the getRouteKeyName method in your model

Helper method

There is a staticfindByUuid method for you to use. Simply:

$user = User::findByUuid($request->input('user_uuid'));

Last updated