🏳🌈 Attla / Laravel Implementation of ULID
MIT License
A PHP port of ulid/javascript with some minor improvements.
UUID can be suboptimal for many uses-cases because:
Instead, herein is proposed ULID:
You can read more here
https://example.com/item/10
composer require attla/ulid
use Attla\Ulid\Factory as UlidFactory;
$ulid = UlidFactory::generate();
echo $ulid; // 01B8KYR6G8BC61CE8R6K2T16HY
echo $ulid->generate(); // 01B8KYR6G8BC61CE8R6K2T16HZ
// Or if you prefer a lowercased output
$ulid = UlidFactory::generate(true);
echo $ulid->get(); // 01b8kyr6g8bc61ce8r6k2t16hy
// If you need the timestamp from an ULID instance
$ulid = UlidFactory::generate();
echo $ulid->toTimestamp(); // 1561622862
// You can also generate a ULID for a specific UNIX-time in milliseconds
$ulid = UlidFactory::fromTimestamp(1593048767015);
// or with a lower cased output: $ulid = UlidFactory::fromTimestamp(1593048767015, true);
echo $ulid->toString(); // 01EBMHP6H7TT1Q4B7CA018K5MQ
Use the methods get()
or toString()
to get the ULID as a string on ULID instances.
When using the migration you should change $table->increments('id') or $table->id() to:
$table->ulid();
Simply, the schema seems something like this.
Schema::create('items', function (Blueprint $table) {
$table->ulid();
....
....
$table->timestamps();
});
If the related model is using an ULID, the column type should reflect that also.
Schema::create('items', function (Blueprint $table) {
$table->ulid();
....
// related model that uses ULID
$table->foreignUlid('category_id');
....
$table->timestamps();
});
The ULID blueprint parameter is optional. But below is an example of how to use it.
Schema::create('categories', function (Blueprint $table) {
$table->ulid($ulidLength);
....
// related model that uses ULID
$table->foreignUlid($column, $foreignColumn, $foreignTable, $ulidLength);
....
$table->timestamps();
});
To set up a model to use ULID, simply use the HasUlid trait.
use Illuminate\Database\Eloquent\Model;
use Attla\Ulid\HasUlid;
class Item extends Model
{
use HasUlid;
}
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
composer test
composer benchmark
This package is licensed under the MIT license © Octha.