Eloquent UUID Package for Laravel

News

July 30th, 2019

global-laravel.jpg

We recently covered a Eloquent UUID package for automatically using a UUID with an Eloquent model. We get quite a few messages about posts and packages related to UUID.

Today we’ll look at another UUID package by James Mills which differs from the other package we’ve shared. The thing I like about this package is the use of a trait vs. using inheritance to accomplish adding UUIDs to models.

The last package we covered, Eloquent UUID, subscribes to the approach of making the UUID field the primary key of the database table. It prefers using class inheritance as the mode of enabling UUID support in your Eloquent models.

James’ package takes a different approach, using a trait that listens for the model’s creating event and stores the UUID automatically as a field that is separate from the primary key.

Using the trait this package provides, you can query the model by UUID as follows:

1Route::get('/user/{uuid}', function($uuid) {
2 try {
3 return App\User::findByUuidOrFail($uuid);
4 } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
5 abort(404);
6 }
7});

You can also scope a query using the withUuid method, which also has a plural version too:

1// Single UUID
2$user = App\User::withUuid($uuid)->first();
3
4// Multiple UUIDs
5$users = App\User::withUuids($uuids)->all();

You can learn more about this package, get full installation instructions, and view the source code on GitHub at jamesmills/eloquent-uuid.

Filed in:

Paul Redmond

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