Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Overview

Laravel Uuid

Total Downloads Build Status codecov.io Latest Stable Version Licence

Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for version 1, 3, 4 and 5 UUIDs are built-in.

What's new in 4.*

Laravel-uuid is now ready for Laravel 8. It has the same requirements so that means PHP 7.3 or PHP 8. Laravel package auto-discovery is enabled, and you can now use the UUID validation. Validation examples are below and in the tests.

For older Laravel or PHP versions use older versions; see below...

What's new in 3.*

Laravel-uuid is now refactored for Laravel 5.5. It has the same requirements so that means PHP 7. Laravel package auto-discovery is enabled, and you can now use the UUID validation. Validation examples are below and in the tests.

Laravel 5.0, 5.1, 5.2, 5.3 and 5.4? use version 2

Laravel 4.*? use version 1

Installation

In Laravel 5.5 laravel-uuid will install via the new package discovery feature so you only need to add the package to your composer.json file

composer require "webpatser/laravel-uuid:^3.0"

after installation you should see

Discovered Package: webpatser/laravel-uuid

and you are ready to go

Basic Usage

To quickly generate a UUID just do

Uuid::generate()

This will generate a version 1 Uuid object with a random generated MAC address.

To echo out the generated UUID, cast it to a string

(string) Uuid::generate()

or

Uuid::generate()->string

Advanced Usage

UUID creation

Generate a version 1, time-based, UUID. You can set the optional node to the MAC address. If not supplied it will generate a random MAC address.

Uuid::generate(1,'00:11:22:33:44:55');

Generate a version 3, name-based using MD5 hashing, UUID

Uuid::generate(3,'test', Uuid::NS_DNS);

Generate a version 4, truly random, UUID

Uuid::generate(4);

Generate a version 5, name-based using SHA-1 hashing, UUID

Uuid::generate(5,'test', Uuid::NS_DNS);

Some magic features

To import a UUID

$uuid = Uuid::import('d3d29d70-1d25-11e3-8591-034165a3a613');

Extract the time for a time-based UUID (version 1)

$uuid = Uuid::generate(1);
dd($uuid->time);

Extract the version of an UUID

$uuid = Uuid::generate(4);
dd($uuid->version);

Eloquent UUID generation

If you want an UUID magically be generated in your Laravel models, just add this boot method to your Model.

/**
 *  Setup model event hooks
 */
public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->uuid = (string) Uuid::generate(4);
    });
}

This will generate a version 4 UUID when creating a new record.

Model binding to UUID instead of primary key

If you want to use the UUID in URLs instead of the primary key, you can add this to your model (where 'uuid' is the column name to store the UUID)

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'uuid';
}

When you inject the model on your resource controller methods you get the correct record

public function edit(Model $model)
{
   return view('someview.edit')->with([
        'model' => $model,
    ]);
}

Validation

Just use like any other Laravel validator.

'uuid-field' => 'uuid'

Or create a validator from scratch. In the example an Uuid object in validated. You can also validate strings $uuid->string, the URN $uuid->urn or the binary value $uuid->bytes

$uuid = Uuid::generate();
$validator = Validator::make(['uuid' => $uuid], ['uuid' => 'uuid']);
dd($validator->passes());

Notes

Full details on the UUID specification can be found on http://tools.ietf.org/html/rfc4122.

Comments
  • Call to undefined method Webpatser\Uuid\UuidFacade::generate() in Laravel 5.5

    Call to undefined method Webpatser\Uuid\UuidFacade::generate() in Laravel 5.5

    When upgrading Laravel from 5.4 to 5.5 I got the following error:

    Call to undefined method Webpatser\\Uuid\\UuidFacade::generate()

    I'm using 'Uuid' => Webpatser\Uuid\Uuid::class, in my aliases.

    My code:

    static::creating(function ($model) {
         $model->{$model->getKeyName()} = Uuid::generate()->string;
    });
    
    opened by dees040 8
  • Add Laravel 5 validation support.

    Add Laravel 5 validation support.

    I needed to be able to validate UUIDs on a Laravel API I'm creating, but couldn't find a solution in Laravel itself. Here's my attempt to create a ServiceProvider that introduces the validation support (it also fixes #5).

    I wouldn't consider this PR complete, however, because it lacks the localization support. Whenever the user does happen to run across a UUID that is invalid, it only says validation.uuid as the message instead of something friendlier.

    I spent some time looking through the Laravel documentation trying to find a way for packages to add non-namespaced localization (or configure the validator to use the namespaced localization key), but it doesn't seem like that's currently possible.

    As I was finalizing the pull request, I noticed that this library also supports MAC-address-like UUIDs (those are considered UUIDs?). I'm not sure the regex I use in the validation function is robust enough to handle validating something like that, so feel free to replace the regex in that with something else.

    I also updated the README with instructions on how to activate the service provider and how to configure the localization on the application's Laravel instance (because like I said above, it doesn't seem like we can configure it in the package for the time being).

    opened by sammarks 5
  • Where can i use this uuid

    Where can i use this uuid

    I like to know in which type of situation I need to use this program. Can you give me some real time scenarios.. which will be easy for me to understand..

    Regards, Vijey

    opened by raghavan2004 4
  • Laravel findOrFail support

    Laravel findOrFail support

    Hi,

    While using the findOrFail(id) method, I noticed that Eloquent returns a record matching a different id than the one I pass in. It does not throw an error, so it took me some time to find this flaw.

    Am I correct to assume that findOrFail() is currently not supported by this package?

    Kind regards,

    Sander

    opened by sandervanhooft 4
  • Lumen 6.3.2 - did not autodiscover - Class 'Uuid' not found

    Lumen 6.3.2 - did not autodiscover - Class 'Uuid' not found

    Hey, I wanted to use this for my API, and after running composer require, I tried to use the library in my code, but was unsuccessfull.

    It seems like Lumen does not know anything about it.

    Help please?

    opened by dodancs 3
  • Many to many relationships

    Many to many relationships

    Hey,

    I have three entities: 'items', 'users', and 'cities'. Users can receive items in certain cities and I want to save where a particular user has received that item. As I could have millions of items in the database, I don't want to use integer ids, so I figured I'd use your uuids like so

    Schema::create('items', function (Blueprint $table) {
                $table->uuid('id');
                $table->string('name');
                $table->timestamps();
                $table->primary('id');
            });
    
    Schema::create('item_user', function (Blueprint $table) {
                $table->increments('id');
                $table->uuid('item_id')->references('id')->on('items');
                $table->integer('user_id')->references('id')->on('users');
                $table->integer('city_id')->nullable();
                $table->timestamps();
            });
    
    Schema::create('cities', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('country_id');
                $table->string('englName');
                $table->string('nativeName');
                $table->timestamps();
            });
    

    and added the following lines in the Item Model class

    public static function boot()
      {
        parent::boot();
        self::creating(function ($model) {
            $model->id = (string) Uuid::generate(4);
        });
      }
        public function users(){
          return $this->belongsToMany('App\User');
        }
    
        public function cities(){
          return $this->belongsToMany('App\City', 'item_user');
    

    However the relationships weren't returning anything even though I filled the database with legitimate testing data. So I started investigating and just put a var_dump on all queries using \DB::connection()->enableQueryLog(); and {{var_dump(DB::getQueryLog())}} finding that the binding for those queries goes wrong. As you can see it uses some integer value even though it should be using the uuid. Do you have any ideas what is going wrong?

    [3]=> array(3) { ["query"]=> string(283) "select "users".*, "item_user"."item_id" as "pivot_ item_id", "item_user"."user_id" as "pivot_user_id" from "users" inner join "item_user" on "users"."id" = "item_user"."user_id" where "item_user"."item_id" in (?)" ["bindings"]=> array(1) { [0]=> int(1) } 
    
    opened by Gerungofulus 3
  • Laravel 5 broken

    Laravel 5 broken

    `

    Whoops, looks like something went wrong.

    1/1 FatalErrorException in PhotosController.php line 40: Class 'App\Http\Controllers\Uuid' not found``

    added it to aliasses...

    opened by renege 3
  • Uuid returns as lowercase, written to database uppercase

    Uuid returns as lowercase, written to database uppercase

    Using UUID via a trait:

    ` <?php

    namespace App;
    
    use Webpatser\Uuid\Uuid;
    trait Uuids
    {
    
        /**
         * Boot function from laravel.
         */
        protected static function boot()
        {
            parent::boot();
    
            static::creating(function ($model) {
                $model->{$model->getKeyName()} = Uuid::generate()->string;
            });
        }
    }`
    

    When creating a record, the uuid is stored in the database uppercase, but it is passed to the return route url in lowercase. When you click on the same record from a list view the url contains the uuid in uppercase. I did not think this was an issue until trying to use Laravel Scout and Algolia Search.

    This causes Algolia to create two records in the index, one with a lower case uuid when the record is created and another with uppercase uuid when the record is modified. Only the uppercase uuid is searchable since it matches the database record.

    Why is this happening and how can I force uppercase UUID only within the trait?

    opened by CHGill 2
  • error: Malformed UTF-8 characters, possibly incorrectly encoded

    error: Malformed UTF-8 characters, possibly incorrectly encoded

    When I want return UUID that generated in the JSON, laravel return this error. I use utf8_encode function like this return utf8_encode(Webpatser\Uuid\Uuid::generate()); and error fixed. after saved UUID in the database and get it, the value is correct and did not generate error anymore. laravel 5.5

    opened by bkhezry 2
  • UUID on Many to Many Relationship

    UUID on Many to Many Relationship

    I have created a trait and applied it to my model. But in other side, How to solve the problem of making uuid in many to many relationship, where we do not make model many to many table?

    Example : we have two model User and Role and we have three tables users , roles and user_role. we have sync code bellow. $create = $user->roles()->sync($roles_id); we get $create with id = '' how to solve the problem?

    opened by faozimipa 2
  • Problem with routing

    Problem with routing

    Hey!

    I use laravel-uuid in my project and I found a problem with routing. I store UUIDs in uuid column and I have also this code in user model:

    // app/User.php
    
    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'uuid';
    }
    

    When I send GET request (for example to http://127.0.0.1:8000/api/v1/users/5af0ed93-5575-4c91-951c-f4b065ea2aea) I get an error:

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `users` where `id` = 1 limit 1)
    

    My router:

    // routes/api.php
    
    Route::prefix('v1')->middleware(['auth:api'])->group(function () {
        Route::resource('users', 'UserController', ['only' => ['update', 'show', 'destroy']]);
    });
    
    opened by lukaszflorczak 2
  • readme and composer.json required php version are different

    readme and composer.json required php version are different

    In the readme the minimum php version listed for 4.* is 7.3 but in the composer.json it has 7.0. dependabot is raising a pr for this when the project php version is 7.2 and it's passing. Either the readme should be updated or the composer.json file

    opened by jclyons52 1
  • RuntimeException error while installing in Laravel version 5.5

    RuntimeException error while installing in Laravel version 5.5

    [RuntimeException]
    Failed to execute git clone --mirror -- 'https://ghp_IkedhLEZ6hksAqjZHfBmRl
    H7jsaJLp21V3Zz:[email protected]/kenarkose/Ownable.git' '/home/dev/.
    cache/composer/vcs/https---github.com-kenarkose-Ownable.git/'

    opened by askaaqib 1
  • Uuid::generate( 4 ) produces a uuid4 without it's rfc defined version information

    Uuid::generate( 4 ) produces a uuid4 without it's rfc defined version information

    I've been troubleshooting parts our our application and came across uuid's that I believe do not have their RFC4122 version information.

    Uuid::generate( 4 )->string

    Example: 14326a6c-184f-11ea-9e97-06aad2cae86c

    A version 4 UUID is defined in RFC 4122: 128 randomly-generated bits with six bits at certain positions set to particular values. the four most significant bits of the 7th byte to 0100'B, so the high nibble is "4" set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of "8", "9", "A", or "B"

    https://www.cryptosys.net/pki/uuid-rfc4122.html https://tools.ietf.org/html/rfc4122#section-4.1.3

    opened by tebruno99 0
  • Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY'

    Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY'

    I have a high load on one of my apps right now. I've never seen this error:

    Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY'

    Should I be worried about NULL collisions as records are being inserted?

    Thanks, btw! I love the package.

    opened by mi-ke-dev 0
  • Validate-function returns true when parameter is not valid uuid

    Validate-function returns true when parameter is not valid uuid

    Validate-function returns true with parameter value "20191015_100_051". The result is the same with any given parameter of length 16. Tested with version 3 on Laravel 5.5.

    opened by kuola 1
Releases(1.3)
Owner
Christoph Kempen
Specializes in building high performance APIs with Laravel/Lumen and Elasticsearch.
Christoph Kempen
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
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
A simple drop-in solution for providing UUID support for the IDs of your Eloquent models.

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

GoldSpec Digital 501 Jan 4, 2023
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
The list of all Algerian provinces and cities according to the official division in different formats: csv, xlsx, php, json, etc.

algeria-cities This repository contains the list of all the administrative provinces and cities in Algeria. The data is up-to-date according to the of

Ramtani Othmane 393 Jan 2, 2023
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 28, 2022
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 30, 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
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
A simple laravel package to validate console commands arguments and options.

Command Validator A simple laravel package to validate console commands arguments and options. Installation Require/Install the package using composer

Touhidur Rahman 20 Jan 20, 2022
A Laravel package that allows you to validate your config values and environment.

Table of Contents Overview Installation Requirements Install the Package Publishing the Default Rulesets Usage Creating a Validation Ruleset Using the

Ash Allen 152 Dec 15, 2022
🛂 Use this package to validate the identity card from your country using laravel validation rules.

Identity Card Checker Laravel Validation Rules Use this package to validate the identity card number from your country Installation You can install th

David Torralbo Pérez 13 Feb 8, 2022
A package to validate email domains in a user registration form

This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM 56 Jul 19, 2022
A package to validate email domains in a user registration form

Laravel Email Domain Rule This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM Innovation 56 Jul 19, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022
A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

Munaf Aqeel Mahdi 1.7k Jan 5, 2023
A Laravel wrapper for spatie/dns. Allows to query and validate DNS records.

A Laravel wrapper for spatie/dns. Allows to query and validate DNS records.

Astrotomic 22 Nov 17, 2022