webpatser / laravel-uuid Goto Github PK
View Code? Open in Web Editor NEWLaravel 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.
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.
Hi all.
I have encountered error after adding UuidServiceProvider::class
in providers and Uuid::class
in alias of config/app.php
,
and running config cache with php artisan config:cache
.
The error is as below:
[Symfony\Component\Debug\Exception\FatalErrorException]
Class Webpatser\Uuid\UuidServiceProvider contains 1 abstract method and mus
t therefore be declared abstract or implement the remaining methods (Illumi
nate\Support\ServiceProvider::register)
As I look into the UuidServiceProvider class, looks like the register method is missing which is required in Laravel 5.2 ServiceProvider
.
Hello, I want to use your library at personal project. But I need a MIT or BSD licensed library. I can not find a license file here. Please add one.
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?
Since https://packagist.org/packages/fzaninotto/faker is now abandoned.
Link to FakerPHP/Faker: https://github.com/FakerPHP/Faker.
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']]);
});
`
added it to aliasses...
How set default value uuid? Help me?
Uuid is not found
error when trying to generate uuid from the controller
Uuid::generate(4);
Uuid::generate()
returns the object. You might want to put Uuid::generate()->string
under Basic Usage so simpletons like myself can get up and running quicker (just my 2c).
Is there any possibility to create a uuid but only with 8 digits, as datatype integer?
Why do these two work the same way?
$someModel = new SomeModel();
$someModel->uuid = Uuid::generate(4);
$someModel->save();
$someModel = new SomeModel();
$someModel->uuid = Uuid::generate(4)->string;
$someModel->save();
In the first one I'm not specifically getting the string but yet it works exactly the same.
If I do dd(Uuid::generate(4))
and dd(Uuid::generate(4)->string)
it prints different things:
Uuid {#327 ▼
#bytes: b"Å\x17ãÆˤAËùTÜ┴\x17┌¨¢"
#hex: null
#string: "8f17c692-d3cf-41d3-9754-9ac117daf9bd"
#urn: null
#version: null
#variant: null
#node: null
#time: null
}
"f48abcbb-fbf7-417e-9493-d67ce86055d0"
So clearly they're different, but when I'm inserting into the database it will automatically get the string key.
Why? Please help me understand this.
When i use both Uuid and Entrust in my model i get an error:
Trait method boot has not been applied, because there are collisions with other trait methods
on App\User
this is my code:
namespace App;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Uuids;
use EntrustUserTrait;
}
I'm having trouble on migration using the following documentation
https://medium.com/@steveazz/setting-up-uuids-in-laravel-5-552412db2088
on migration table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->uuid('api_token'); ....
Error:
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column
'api_token' at row 1 (SQL: insert into `users` (`name`, `email`, `password`,
`api_token`, `id`, `updated_at`, `created_at`) values (ryai, ryanpagaduan23@g
mail.com, $2y$10$dc2KEaRkO19R.Thub8I11./AXezb3qoCyqumuGMfbSMhwF70YHCIe, 8560b
59ebbfc01d882175c39ce860480a06b4c6a6aa56382032e4a8c2c8a, a3674340-2de9-11e9-a
087-c93c351f4ba4, 2019-02-11 10:41:50, 2019-02-11 10:41:50))
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
Cannot extract UUID value from generate
I get strange results when using Uuid::import
on a uuid returned from an SQL Server uniqueidentifier
filled by the SQL default newsequentialid()
like this:
>>> $uid = Webpatser\Uuid\Uuid::import(App\Deployment::first()->id)
=> Webpatser\Uuid\Uuid {#742}
>>> dd($uid)
Webpatser\Uuid\Uuid {#742
#bytes: b"""
k\x07[‚ìD\x11å€Ü\x00\x15]\n
¼T
"""
#hex: null
#string: "6b075b82-ec44-11e5-80dc-00155d0abc54"
#urn: null
#version: null
#variant: null
#node: null
#time: null
}
>>> App\Deployment::find($uid->string)
=> null
The last bit should have returned the model, from which I previously got the uuid.
The actual uuid as I see it in SQL Server Management Studio looks like this though:
SQL: 825B076B-44EC-E511-80DC-00155D0ABC54
PHP: 6B075B82-EC44-11E5-80DC-00155D0ABC54
The first two blocks seem to be in reversed order.
When using the first uuid I can find the model as expected:
>>> App\Deployment::find('825B076B-44EC-E511-80DC-00155D0ABC54')
=> App\Deployment {#734}
Am I missing something here?
Hi,
I'm trying to use your great library in a Lumen project without using Facades (imho Facades are userland tools).
I'd also love to see some info on how to implement this in Lumen.
I've managed so far by creating a custom UuidServiceProvider that includes a register() function, and I replaced all facade calls. I'll make a PR later on so you can review my changes..
Thanks for this already!
Kind regards
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?
How to get last inserted id ?
users -> user_agencies -> agency
cannot create user from agency->users()->create(...)
public function users() {
return $this->belongsToMany('App\User', 'user_agencies', 'agency_id', 'user_id');
}
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into user_agencies
(agency_id
, user_id
) values (e8c92d00-b27d-11e8-94d6-39aa45ecfc56, e8dea9f0-b27d-11e8-8c75-8d673446facb))
I installed uuid but uuid not creating. i added alias code in config /app.php and Uuid::generate() in controller function
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.
Fatal error: Class 'App\Http\Controllers\Uuid' not found on laravel 5.2
It seems counter-intuitive that it is not possible to generate a specific version of a UUID using the Uuid::VERSION_*
constants e.g. Uuid::generate(Uuid::VERSION_4);
. As this library currently supports PHP >= 7.0.0 the use of private visibility constants isn't possible without a major version bump.
One solution is making these constants private (possibly static) properties. This would remove them from the public scope and avoid any confusion around their use.
The other possible solution is to add them as cases in the switch statement that determines which type of UUID to generate:
switch ((int)$ver) {
// [...]
case 4:
case self::VERSION_4:
return new static(static::mintRand());
// [...]
Thoughts?
composer.json had:
"webpatser/laravel-uuid": "^2.0.1",
deployed as usual and composer pulled in versions : * 2.2
Any visitor with a UUID in cookie is breaking.
Symfony\Component\Debug\Exception\FatalErrorException: Exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Method Webpatser\Uuid\Uuid::__toString() must not throw an exception, caught ErrorException: Undefined property: Webpatser\Uuid\Uuid::$string' in /home/forge/payday.live/releases/20170906013516/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:67
Rolled composer back to:
"webpatser/laravel-uuid": "2.0.1",
Fixed my problem.
2.2 should be backward compatible to 2.0.1 yes??
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) }
It'd be nice to have a way to determine if supplied UUID is a valid one. Something like
Uuid::isValid($supposedUUID)
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.
I created a parent class Model which I inherit in other model classes. The Parent class Model carries this logic
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string) Uuid::generate(4);
});
}
But as the factory runs on the second item, the same UUID generated on the first item is used. Kindly assist with implementation on factories. This is my seeder class
factory(App\User::class, 50)->create();
I get it is not an issue with the package but kindly help. This is my first project with non-incrementing ids
Not really understand how this works at all but I need to generate a unique string from a real MAC address
Uuid::generate(5, 'AABBCCDDEEFF', Uuid::NS_DNS);
But I need the result to be always the same for the same MAC address whenever I perform this task (now or future). Do you think this fits my needs?
Error fixed. should not add the package in the providers.
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
can you confirm @webpatser?
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?
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
When updating, this warning is displayed
deprecated [email protected]: Use uuid module instead
just changed the following code ,got the issue,thanks!
// CUSTOM_SERVICE_UUID_BASE 0000ff00-0000-1000-8000-00805f9b34fb
#define CUSTOM_SERVICE_UUID_BASE {0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
0x00, 0x10, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00}
Can you provide the configuration for Lumen
Could it be possible to split the Uuid class to another repository as a dependency, so that I could use that package in a non-laravel project?
Thanks
OpenSSL uses openssl_random_pseudo_bytes() to generate its randomness, however there are known issues with this causing collisions in environments under apache/php-fpm, when instances are forked, the parent and child processes can end up generating the same uuid.
You can read all about it at https://benramsey.com/blog/2016/04/ramsey-uuid/ under the section "WHEN UUIDS COLLIDE".
The solution to this problem was to avoid using openSSL as a fallback for generating random bytes and add paragonie/random_compat as a fallback and use random_btyes() for PHP>=7
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;
});
Didn't see anything in the documentation, so just checking if this package is compatible with Laravel 5?
Is this supposed to work outside of laravel? Not sure if this is by design or not...?
composer.json
{
"require": {
"webpatser/laravel-uuid":"2.*"
}
}
uuid-test.php
<?php
require('vendor/autoload.php');
$uuid = Uuid::generate(4);
echo $uuid;
?>
Test
% php uuid-test.php
PHP Fatal error: Uncaught Error: Class 'Uuid' not found in /Users/username/Desktop/mturk-php/uuid-test.php:7
Stack trace:
#0 {main}
thrown in /Users/username/Desktop/mturk-php/uuid-test.php on line 7
Even though the chance is really really slim, I already have 2 UUID collisions in the last 4 months. Given there are not even 50000 rows in the table, I am wondering.
I am using V4 of the UUID and it gets created on insert.
Interesting Error. My Mac is running PHP 7.3.24. When I attempt to add and build the error below is thrown.
[InvalidArgumentException]
Package webpatser/laravel-uuid at version ^3.0 has a PHP requirement incompatible with your PHP version, PHP extensions and Composer version
Any thoughts?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.