Eloquent UUID Package for Laravel
Published on by Paul Redmond
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:
Route::get('/user/{uuid}', function($uuid) { try { return App\User::findByUuidOrFail($uuid); } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) { abort(404); }});
You can also scope a query using the withUuid
method, which also has a plural version too:
// Single UUID$user = App\User::withUuid($uuid)->first(); // Multiple UUIDs$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.