Git Product home page Git Product logo

laravel-ulid's Introduction

Laravel ULID

Laravel package to generate ULID (Universally Unique Lexicographically Sortable Identifier), which also contains trait for your models that will let you generate ULID ids for your Eloquent models automatically. Based on robinvdvleuten/php-ulid.

What is a ULID?

In many cases universally unique identifier (UUID) can be suboptimal for many uses-cases because:

  • It isn't the most character efficient way of encoding 128 bits of randomness
  • UUID v1/v2 is impractical in many environments, as it requires access to a unique, stable MAC address
  • UUID v3/v5 requires a unique seed and produces randomly distributed IDs, which can cause fragmentation in many data structures
  • UUID v4 provides no other information than randomness which can cause fragmentation in many data structures

Instead, ULID offers:

  • 128-bit compatibility with UUID
  • 1.21e+24 unique ULIDs per millisecond
  • Lexicographically sortable!
  • Canonically encoded as a 26 character string, as opposed to the 36 character UUID
  • Uses Crockford's base32 for better efficiency and readability (5 bits per character)
  • Case insensitive
  • No special characters (URL safe)

You can read more here

What are the benefits?

  1. With distributed systems you can be pretty confident that the primary key’s will never collide.

  2. When building a large scale application when an auto increment primary key is not ideal.

  3. It makes replication trivial (as opposed to int’s, which makes it REALLY hard)

  4. Safe enough doesn’t show the user that you are getting information by id, for example https://example.com/item/10

Installation

You can install this package via composer using this command:

 composer require rorecek/laravel-ulid:^2.0

Laravel 5.5+

There is nothing else to do as the service provider and facade are going to be automaticaly discovered.

Laravel 5.3 and 5.4

You must install the service provider and facade:

// config/app.php
'providers' => [
    ...
    Rorecek\Ulid\UlidServiceProvider::class,
];

...

'aliases' => [
    ...
    'Ulid' => Rorecek\Ulid\Facades\Ulid::class,
];

Usage

Migrations

When using the migration you should change $table->increments('id') to:

$table->char('id', 26)->primary();

Simply, the schema seems something like this.

Schema::create('items', function (Blueprint $table) {
  $table->char('id', 26)->primary();
  ....
  ....
  $table->timestamps();
});

If the related model is using an ULID, the column type should reflect that also.

Schema::create('items', function (Blueprint $table) {
  $table->char('id', 26)->primary();
  ....
  // related model that uses ULID
  $table->char('category_id', 26);
  $table->foreign('category_id')->references('id')->on('categories');
  ....
  $table->timestamps();
});

Models

To set up a model to use ULID, simply use the HasUlid trait.

use Illuminate\Database\Eloquent\Model;
use Rorecek\Ulid\HasUlid;

class Item extends Model
{
  use HasUlid;
}

Controller

When you create a new instance of a model which uses ULIDs, this package will automatically add ULID as id of the model.

// 'HasUlid' trait will automatically generate and assign id field.
$item = Item::create(['name' => 'Awesome item']);
echo $item->id;
// 01brh9q9amqp7mt7xqqb6b5k58

Support

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!

License

The MIT License (MIT). Pavel Rorecek

laravel-ulid's People

Contributors

richardnbanks avatar rorecek avatar vov41knk avatar xatta-trone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

laravel-ulid's Issues

HasUlid and ModelOserver

Hello!

Huston, i have a problem :)

I making a package with some models using ULID
Well, problem in in ModelObservers, which overwrites any your magic methods and treir methods.

Any suggestion?

PHP 8 Support

When you have a moment please could you update composer.json to allow support for PHP 8?

I can confirm the package is working perfectly on PHP 8. At the moment to start a PHP 8, Laravel 8 built using your package you need run composer with --ignore-platform-reqs flag

Hopefully you just need to update your require PHP ^7.0|^8.0 in your composer.json to enable support.

Many thanks

Mat

Laravel 6 Upgrade

Would it be possible to change composer from:

"laravel/framework": "^5.3"

to:

"laravel/framework": "^5.3|^6.0"

Many thanks

Left join id is null when $incrementing = false

Thanks for the library!

I have the following:

Tables:
CREATE TABLE font_awesome_categories (
    `id` binary(26) NOT NULL,
    `name` varchar(50) NOT NULL,
);

CREATE TABLE font_awesome_icons (
    `id` binary(26) NOT NULL,
    `type` varchar(10) NOT NULL,
    `prefix` varchar(3) NOT NULL,
    `icon` varchar(50) NOT NULL,
    `unicode` varchar(10) NOT NULL,
);

CREATE TABLE font_awesome_icon_categories (
    `id` binary(26) NOT NULL,
    `category_id` binary(26) NOT NULL,
    `icon_id` binary(26) NOT NULL,
);

SQL:
select fai.id, fac.category_id, type, prefix, icon, unicode 
from font_awesome_icons fai 
left join font_awesome_icon_categories fac on fac.icon_id = fai.id 
order by icon asc;

Model:
class FontAwesomeIcon extends Model
{
    public function categories()
    {
        return $this->hasManyThrough(            
            'App\Models\ContentEditor\FontAwesomeCategory', 
            'App\Models\ContentEditor\FontAwesomeIconCategory',
            'icon_id', // Foreign key on faIconCategory table...
            'id', // Foreign key on faCategory table...
            'id', // Local key on faIcon table...
            'category_id' // Local key on faIconCategory table...
        );
    }
}

Query:
$result = FontAwesomeIcon::leftJoin('font_awesome_icon_categories', 'font_awesome_icon_categories.icon_id', '=', 'font_awesome_icons.id')
	->with('categories')
	->orderBy('icon')
	->get();

The id field is null:

attributes: array:11 [▼
	"id" => null
	"type" => "brands"
	"prefix" => "fab"
	"icon" => "500px"
	"unicode" => "f26e"
	"created_at" => null
	"updated_at" => null
	"deleted_at" => null
	"category_id" => null
]

Although I can resolve it for now, by adding a select to the query:

->select(
	'font_awesome_icons.id as id', 
	'font_awesome_icon_categories.category_id', 
	'font_awesome_icons.type',
	'font_awesome_icons.prefix',
	'font_awesome_icons.icon',
	'font_awesome_icons.unicode'
)

How about add getIncrementing() for `HasUlid` trait ?

Add getIncrementing for HasUlid trait

...
    public function getIncrementing()
    {
        return false;
    }
...

It make Model more clear

use Illuminate\Database\Eloquent\Model;
use Rorecek\Ulid\HasUlid;

class Item extends Model
{
  use HasUlid;
}

Key Type needs to be defined for "many" relationships

When using "many" relationships error like the following is produced:

SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: character = integer
LINE 1: select * from "files" where "files"."fileable_id" in (1, 1, ...

HINT:  No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select * from "files" where "files"."fileable_id" in (1, 1, 1, 1, 1, 1, 1, 1, 1, 1) and "files"."fileable_type" = App\\Contract and "files"."deleted_at" is null)

This can be fixed by adding the getKeyType function to the trait and setting it to string.

Inconsistent order

If records are create too quickly the ordering of this Ulid is not correct.

I have added an example of what is being generated with a running integer number. As you can see, the order under tax_report_id differs from the ulid generated.

image (2)
.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.