• Stars
    star
    449
  • Rank 97,328 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This package allows you to easily work with UUIDs in your Laravel models

Laravel Model UUIDs

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads License Dependency Status Buy us a tree

Introduction

I find myself using UUID across multiple projects of late, and packaged up this functionality rather than copying and pasting it from project to project.

Note: this package explicitly does not disable auto-incrementing on your Eloquent models. In terms of database indexing, it is generally more efficient to use auto-incrementing integers for your internal querying. Indexing your uuid column will make lookups against that column fast, without impacting queries between related models.

For more information, check out this post on storing and working with UUID in an optimised manner.

Take a look at laravel-efficient-uuid if you want to make it easy to generate migrations that efficiently store UUID in your database.

If you require compatibility with ramsey/uuid >= 4.1, please use version >= 6.2.0 of this package.

As of version 7.1.0 this package supports only UUID versions 1 (uuid1), 4 (uuid4), 6 (uuid6 - ordered) and ordered (Laravel's ordered UUID v4) and 7 (uuid7).

This package supports Laravel 10 and PHP 8.1 as minimum.

Code Samples

In order to use this package, you simply need to import and use the trait within your Eloquent models.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Dyrynda\Database\Support\GeneratesUuid;

class Post extends Model
{
    use GeneratesUuid;
}

It is assumed that you already have a field named uuid in your database, which is used to store the generated value. If you wish to use a custom column name, for example if you want your primary id column to be a UUID, you can define a uuidColumn method in your model.

class Post extends Model
{
    public function uuidColumn(): string
    {
        return 'custom_column';
    }
}

You can have multiple UUID columns in each table by specifying an array in the uuidColumns method. When querying using the whereUuid scope, the default column - specified by uuidColumn will be used.

class Post extends Model
{
    public function uuidColumns(): array
    {
        return ['uuid', 'custom_column'];
    }
}

The package will use uuid as the column name to store the generated UUID value by default. If you prefer a different name, you may change the model-uuid.column_name config variable.

You may also override the uuidColumn method on a per-model basis.

By default, this package will use UUID version 4 values, however, you are welcome to use uuid1, uuid4, uuid6, or uuid7 by specifying the protected property $uuidVersion in your model. Should you wish to take advantage of ordered UUID (version 4) values that were introduced in Laravel 5.6, you should specify ordered as the $uuidVersion in your model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Dyrynda\Database\Support\GeneratesUuid;

class Post extends Model
{
    use GeneratesUuid;

    public function uuidVersion(): string
    {
        return 'uuid5';
    }
}

Whilst not recommended, if you do choose to use a UUID as your primary model key (id), be sure to configure your model for this setup correctly. Not updating these properties will lead to Laravel attempting to convert your id column to an integer, which will be cast to 0. When used in combination with laravel-efficient-uuid, this casting will result in a Ramsey\Uuid\Exception\InvalidUuidStringException being thrown.

<?php

namespace App;

use Dyrynda\Database\Support\GeneratesUuid;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use GeneratesUuid;

    public $incrementing = false;

    protected $keyType = 'string';
}

This trait also provides a query scope which will allow you to easily find your records based on their UUID, and respects any custom field name you choose.

// Find a specific post with the default (uuid) column name
$post = Post::whereUuid($uuid)->first();

// Find multiple posts with the default (uuid) column name
$post = Post::whereUuid([$first, $second])->get();

// Find a specific post with a custom column name
$post = Post::whereUuid($uuid, 'custom_column')->first();

// Find multiple posts with a custom column name
$post = Post::whereUuid([$first, $second], 'custom_column')->get();

If you use the suggested laravel-efficient-uuid package, you will need to add a cast to your model in order to correctly set and retrieve your UUID values. This will ensure your UUIDs are written to your (MySQL) database as binary and presented as strings.

<?php

namespace App;

use Dyrynda\Database\Casts\EfficientUuid;
use Dyrynda\Database\Support\GeneratesUuid;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use GeneratesUuid;

    protected $casts = [
        'uuid' => EfficientUuid::class,
    ];
}

Route model binding

From 6.5.0, should you wish to leverage implicit route model binding on your uuid field, you may use the BindsOnUuid trait, which will use the configured uuidColumn by default.

<?php

namespace App;

use Dyrynda\Database\Support\BindsOnUuid;
use Dyrynda\Database\Support\GeneratesUuid;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use BindsOnUuid, GeneratesUuid;
}

Should you require additional control over the binding, or are using < 6.5.0 of this package, you may override the getRouteKeyName method directly.

public function getRouteKeyName(): string
{
    return 'uuid';
}

If you are using the laravel-efficient-uuid package, implicit route model binding won't work out of the box.

Laravel will execute the query using the string representation of the uuid field when querying against the binary data stored in the database. In this instance, you will need to explicitly bind the parameter using the included scope in your RouteServiceProvider:

// app/Providers/RouteServiceProvider.php

public function boot()
{
    Route::bind('post', function ($post) {
        return \App\Post::whereUuid($post)->first();
    });
}

Installation

This package is installed via Composer. To install, run the following command.

composer require dyrynda/laravel-model-uuid

If you wish to override default configuration, you may publish the configuration file to your application.

php artisan vendor:publish --tag=model-uuid-config

Support

If you are having general issues with this package, feel free to contact me on Twitter.

If you believe you have found an issue, please report it using the GitHub issue tracker, or better yet, fork the repository and submit a pull request.

If you're using this package, I'd love to hear your thoughts. Thanks!

Treeware

You're free to use this package, but if it makes it to your production environment you are required to buy the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you support this package and contribute to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees here

Read more about Treeware at treeware.earth

More Repositories

1

laravel-cascade-soft-deletes

Cascading deletes for Eloquent models that implement soft deletes
PHP
935
star
2

laravel-efficient-uuid

PHP
305
star
3

phpstorm-laravel-code-style

PhpStorm code style to meet Laravel's contribution guidelines
293
star
4

laravel-defibrillator

Ensure your Laravel applications keep a normal pulse
PHP
167
star
5

laravel-make-user

A simple Artisan command to create application users
PHP
109
star
6

laravel-nullable-fields

Handles saving empty fields as null for Eloquent models
PHP
104
star
7

dotfiles

Lua
57
star
8

nomad

Laravel-style database migrations wherever they may roam
PHP
56
star
9

vagabond

Eloquent without a home
PHP
48
star
10

founder

Laravel starter application
PHP
48
star
11

carbon.vim

A Vim port of the IntelliJ Carbon theme
Vim Script
41
star
12

Laravel.tmTheme

A Sublime Text 3 theme based on the Laravel documentation colour scheme
40
star
13

founder-style

Founder repository style guide
17
star
14

laravel-owns-models

PHP
15
star
15

readme-generator

Generate README files that rock!
HTML
15
star
16

laravel-google-cse

Laravel wrapper for the Google Custom Search Engine API
PHP
9
star
17

laravel-ldap

Leverage Laravel's middleware to ensure your LDAP-authenticated users stay that way
PHP
6
star
18

git-workflow

A git workflow for facilitating client-facing User Acceptance Testing
6
star
19

RestClient

A REST API Client
PHP
4
star
20

laracasts-saving-json-into-database

Tests and implementation for forum post
JavaScript
4
star
21

terminable-jobs

PHP
3
star
22

telstra-sms

PHP
2
star
23

dyryme

dyry.me link shortener
PHP
2
star
24

amber-electric-php

PHP
2
star
25

zsh-completions

zsh completion scripts
Shell
1
star
26

simple-menu

PHP
1
star
27

chalrynda-blog

Michael & Rhiannon's travel blog
CSS
1
star
28

foods-for-life

Foods For Life Bedrock-based WordPress site
PHP
1
star
29

devdojo-events

PHP
1
star
30

deckset

1
star
31

bbc-good-food

PHP
1
star
32

hemp

PHP
1
star
33

s3upload

Code for blog series on uploading files to Amazon S3 from the browser
PHP
1
star