A simple drop-in solution for providing UUID support for the IDs of your Eloquent models.

Overview

Eloquent UUID

GitHub stars

GitHub tag (latest SemVer) Build status Packagist PHP from Packagist Packagist

Introduction

A simple drop-in solution for providing UUID support for the IDs of your Eloquent models.

Both v1 and v4 IDs are supported out of the box, however should you need v3 or v5 support, you can easily add this in.

Installing

Reference the table below for the correct version to use in conjunction with the version of Laravel you have installed:

Laravel This package
v5.8.* v1.*
v6.* v6.*
v7.* v7.*
v8.* v8.*

You can install the package via composer:

composer require goldspecdigital/laravel-eloquent-uuid:^8.0

Usage

There are two ways to use this package:

  1. By extending the provided model classes (preferred and simplest method).
  2. By using the provided model trait (allows for extending another model class).

Extending model

When creating a Eloquent model, instead of extending the standard Laravel model class, extend from the model class provided by this package:

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;

class BlogPost extends Model
{
    //
}

Extending user model

The User model that comes with a standard Laravel install has some extra configuration which is implemented in its parent class. This configuration only consists of implementing several interfaces and using several traits.

A drop-in replacement has been provided which you can use just as above, by extending the User class provided by this package:

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    //
}

Using trait

As an alternative to extending the classes in the examples above, you also have the ability to use the provided trait instead. This requires a more involved setup process but allows you to extend your models from another class if needed:

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Uuid;
use Illuminate\Database\Eloquent\Model;

class BlogPost extends Model
{
    use Uuid;
    
    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
}

Generating UUIDs

If you don't specify the value for the primary key of your model, a UUID will be automatically generated. However, if you do specify your own UUID then it will not generate one, but instead use the one you have explicitly provided. This can be useful when needing the know the ID of the model before you have created it:

// No UUID provided (automatically generated).
$model = Model::create();
echo $model->id; // abb034ae-fcdc-4200-8094-582b60a4281f

// UUID explicity provided.
$model = Model::create(['id' => '04d7f995-ef33-4870-a214-4e21c51ff76e']);
echo $model->id; // 04d7f995-ef33-4870-a214-4e21c51ff76e

Specifying UUID versions

By default, v4 UUIDs will be used for your models. However, you can also specify v1 UUIDs to be used by setting the following property/method on your model:

When extending the class

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;

class BlogPost extends Model
{
    /**
     * The UUID version to use.
     *
     * @var int
     */
    protected $uuidVersion = 1;
}

When using the trait

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Uuid;
use Illuminate\Database\Eloquent\Model;

class BlogPost extends Model
{
    use Uuid;

    /**
     * The UUID version to use.
     *
     * @return int
     */
    protected function uuidVersion(): int
    {
        return 1;
    }
}

Support for v3 and v5

Should you need support for v3 or v5 UUIDs, you can simply override the method which is responsible for generating the UUIDs:

<?php

namespace App\Models;

use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;

class BlogPost extends Model
{
    /**
     * @throws \Exception
     * @return string
     */
    protected function generateUuid(): string
    {
        // UUIDv3 has been used here, but you can also use UUIDv5.
        return Uuid::uuid3(Uuid::NAMESPACE_DNS, 'example.com')->toString();
    }
}

Creating models

In addition of the make:model artisan command, you will now have access to uuid:make:model which has all the functionality of the standard make:model command (with exception of not being able to create a pivot model):

php artisan uuid:make:model Models/Post --all

Database migrations

The default primary ID column used in migrations will not work with UUID primary keys, as the default column type is an unsigned integer. UUIDs are 36 character strings so we must specify this in our migrations:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table): void {
            // Primary key.
            $table->uuid('id')->primary();
        });
    }
}

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table): void {
            // Primary key.
            $table->uuid('id')->primary();
        
            // Foreign key.
            $table->uuid('user_id');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

Running the tests

To run the test suite you can use the following command:

composer test

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Comments
  • Missing documentation for migrations table

    Missing documentation for migrations table

    Great package! I'm just missing some documentation on how the migrations table should look like.

    I used to use:

    $table->uuid('user_id');
    

    But I am getting error:

    SQLSTATE[01000]: Warning: 1265 Data truncated for column 'user_id' at row 1
    

    When inserting data. I assume this is because of a wrong type?

    documentation 
    opened by simplenotezy 10
  • relationship model uuid

    relationship model uuid

    I have relationship table that connects 2 other tables together (let say post _tags) this table only gets id of post and id of tags therefore this table does not have model (doesn't need one), now when I store my post tags with sync() method. It leaves id column empty which cause errors while storing my posts.

    Any solution to that?

    question 
    opened by robertnicjoo 7
  • MustVerifyEmail not working

    MustVerifyEmail not working

    When using the laravel "MustVerifyEmail", with the "GoldSpecDigital\LaravelEloquentUUID\Foundation\Auth\User" the user is still able to log in even without confirming their emails.

    bug question 
    opened by Escarter 6
  • Create UUID in seeder

    Create UUID in seeder

    How can I create UUID in seeder file?

    Sample

           DB::table('brands')->delete();
    
            $brands = array(
                array(
                    'id' => '',  // how to create this?
                    'name' => 'No Brand',
                    'slug' => 'no-brand',
                    'description' => null,
                    'photo' => null,
                    'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                    'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
                ),
            );
            
            DB::table('brands')->insert($brands);
    
    question 
    opened by robertnicjoo 5
  • Laravel 9

    Laravel 9

    I see that there is already a pull request to support Laravel 9 #47. Any estimates on when this will be merged and published?

    Thank you for your work!

    question 
    opened by davisriska 4
  • Laravel 9.x Compatibility

    Laravel 9.x Compatibility

    This is an automated pull request from Shift to update your package code and dependencies to be compatible with Laravel 9.x.

    Before merging, you need to:

    • Checkout the l9-compatibility branch
    • Review all comments for additional changes
    • Thoroughly test your package

    If you do find an issue, please report it by commenting on this PR to help improve future automation.

    opened by laravel-shift 4
  • Integrity constraint violation: 19 NOT NULL

    Integrity constraint violation: 19 NOT NULL

    Hi there,

    I have tried the package, but this error not present in normal model insertion

    SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: client_service.id (SQL: insert into "client_service" ("client_id", "detail", "service_id", "start", "user_id") values (e5cbdc0c-e23c-4df3-9908-a1a52de45311, VDSVDS, d50c2578-75d7-4b96-b8d7-c960e624734a, 2020-05-16 00:00:00, 3f7d6572-3135-4d62-8d63-a03e7a5a363b))
    

    the code if u want see:

    
        /**
         * @param Request $request
         * @return \Illuminate\Http\RedirectResponse
         */
        public function create(Request $request)
        {
            $request->validate([
                'id' => 'max:255|exists:clients',
                'service_id' => 'max:255|required|exists:services,id',
                'start' => 'max:255',
                'detail' => 'max:255',
            ]);
    
            \App\Client::find($request->id)->services()
                ->attach($request->service_id, [
                    'user_id' => auth()->id(),
                    'start' => Carbon::parse(str_replace('/', '-', $request->start))->toDate(),
                    'detail' => $request->detail ?? '',
                ]);
    
            return back()->with('success', __('Service has been created'));
        }
    

    i have restored normal id for the moment.. tel me updates

    bug invalid 
    opened by MwSpaceLLC 4
  • UUID on pivot

    UUID on pivot

    hi, is there a way of creating uuid on pivot? on seeding, I'm getting General error: 1364 Field 'id' doesn't have a default value

    my model is..

    use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;
    class BoardPost extends Model
    {
        use Uuid;
        
        public $incrementing = false;
        protected $keyType = 'string';
        protected $primaryKey = 'id';
        
        public static function boot()
        {
            parent::boot();
            self::creating(function ($model) {
                $uuid = (string) Uuid::generate(4);
                $model->id = $uuid;
            });
        }
    }
    
    
    opened by jayenne 3
  • doesn't work with method 'with'

    doesn't work with method 'with'

    This lib doesn't work with function 'with' for example Dataset::with('keywords')->get();

    return

    SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: uuid = integer LINE 1: ..."keyword_id" where "dataset_keyword"."dataset_id" in (0, 61,... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select "keyword".*, "dataset_keyword"."dataset_id" as "pivot_dataset_id", "dataset_keyword"."keyword_id" as "pivot_keyword_id", "dataset_keyword"."order" as "pivot_order" from "keyword" inner join "dataset_keyword" on "keyword"."id" = "dataset_keyword"."keyword_id" where "dataset_keyword"."dataset_id" in (0, 61, 6, 0, 0) order by "order" asc)
    
    opened by howkins 3
  • Backport Uuid trait to Laravel v5.8

    Backport Uuid trait to Laravel v5.8

    Hi there,

    Am I right if I think the Uuid trait is not available for laravel 5.8.* (using v1.1.0)? Would it be possible to backport this? Or are there specific reasons to not go there? :)

    Thanks, Glenn

    enhancement 
    opened by glenncoppens 3
  • Create Custom Column (ID)

    Create Custom Column (ID)

    I have an issue for when custom id create when booting method "Declaration of App\Http\Core\Helper\Helpers::boot() must be compatible with GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model::boot(): void" I thought that it is a feature and can implement for manually created for custom Id at the model class with Trait. I hope you add this feature to the next released version.

    question 
    opened by MgHtinLynn 3
Releases(v9.0.0)
Owner
GoldSpec Digital
GoldSpec Digital is a trusted, expressive and collaborative website and app development agency based in the UK.
GoldSpec Digital
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

ΛÐģi 25 Aug 31, 2022
Use auto generated UUID slugs to identify and retrieve your Eloquent models.

Laravel Eloquent UUID slug Summary About Features Requirements Installation Examples Compatibility table Alternatives Tests About By default, when get

Khalyomede 25 Dec 14, 2022
Friendly prefixed IDs for Laravel models

Friendly prefixed IDs for Laravel models Prefixing an id will help users to recognize what kind of id it is. Stripe does this by default: customer ids

Spatie 139 Dec 25, 2022
This package provides a trait that will generate a unique uuid when saving any Eloquent model.

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique uuid when saving any Eloquent model. $model = new

Abdul Kudus 2 Oct 14, 2021
Generate UUID for a Laravel Eloquent model attribute

Generate a UUIDv4 for the primary key or any other attribute on an Eloquent model.

Alex Bouma 4 Mar 1, 2022
Tag support for Laravel Eloquent models - Taggable Trait

Laravel Taggable Trait This package is not meant to handle javascript or html in any way. This package handles database storage and read/writes only.

Rob 859 Dec 11, 2022
Package with small support traits and classes for the Laravel Eloquent models

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

Martin Kluska 3 Feb 10, 2022
This package lets you add uuid as primary key in your laravel applications

laravel-model-uuid A Laravel package to add uuid to models Table of contents Installation Configuration Model Uuid Publishing files / configurations I

salman zafar 10 May 17, 2022
A laravel package to attach uuid to model classes

Laravel Model UUID A simple package to generate model uuid for laravel models Installation Require the package using composer: composer require touhid

null 10 Jan 20, 2022
Use UUID or Ulid as optional or primary key in Laravel.

Laravel OptiKey Use UUID or Ulid as optional or primary key in Laravel. composer require riipandi/laravel-optikey This package adds a very simple trai

Aris Ripandi 33 Nov 4, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
Sortable behaviour for Eloquent models

Sortable behaviour for Eloquent models This package provides a trait that adds sortable behaviour to an Eloquent model. The value of the order column

Spatie 1.2k Dec 22, 2022
This package gives Eloquent models the ability to manage their friendships.

Laravel 5 Friendships This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Alex Kyriakidis 690 Nov 27, 2022
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 955 Dec 25, 2022
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 879 Dec 30, 2022
cybercog 996 Dec 28, 2022
Create presenters for Eloquent Models

Laravel Presentable This package allows the information to be presented in a different way by means of methods that can be defined in the model's pres

The Hive Team 67 Dec 7, 2022