Eloquent UUID Package for Laravel

Eloquent UUID Package for Laravel

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.


Filed in: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Engineer
Remote okay (must already live in USA)
Hawthorne Effect
Senior Software Engineer (Remote - Contract)
Remote
Koodi Systems
PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
Software Developer
Eindhoven
Simac IDS
Application Developer Level II (CakePHP / MySql / Vue.js)
Lancaster, PA
Harbor Compliance
FULL STACK LARAVEL DEVELOPER
LONDON - WEST END
AMPERSAND HEATLH
Mid/Senior Laravel Developer - U.S. Only
Kenner, Louisiana
Profit Miner Technologies