PHPackages                             firevel/model-random-id - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. firevel/model-random-id

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

firevel/model-random-id
=======================

Model random ID generator for Laravel.

0.0.4(1mo ago)110.1k↓52.8%MITPHP

Since Oct 14Pushed 1mo agoCompare

[ Source](https://github.com/firevel/model-random-id)[ Packagist](https://packagist.org/packages/firevel/model-random-id)[ RSS](/packages/firevel-model-random-id/feed)WikiDiscussions master Synced today

READMEChangelog (4)DependenciesVersions (5)Used By (0)

Model Random ID
===============

[](#model-random-id)

A Laravel trait that automatically assigns a cryptographically random integer as the primary key of an Eloquent model. Ids fit in a MySQL `BIGINT` column and stay within JavaScript's `Number.MAX_SAFE_INTEGER`, so they round-trip safely through JSON and JS clients.

Why random BIGINT?
------------------

[](#why-random-bigint)

Distributed databases such as [Cloud Spanner](https://cloud.google.com/spanner) and [Firestore](https://cloud.google.com/firestore) suffer hotspots when ids are monotonically incrementing. [UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier) avoid that problem but are long, hurt index locality, and look ugly in URLs. A random BIGINT is the middle ground — fixed-width, numeric, indexable, and collision-resistant within the 2^53 range.

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require firevel/model-random-id
```

Usage
-----

[](#usage)

Make the primary key a BIGINT in your migration:

```
Schema::create('posts', function (Blueprint $table) {
    $table->bigInteger('id')->primary();
    // ... other columns
});
```

Add the trait to your model:

```
use Firevel\ModelRandomId\HasRandomId;

class Post extends Model
{
    use HasRandomId;
}
```

That's it. The trait disables auto-increment for you and assigns a random id on `saving` if the key column is empty.

```
$post = Post::create(['title' => 'Hello']);
$post->id; // e.g. 7193428815320495
```

### Using a non-primary-key column

[](#using-a-non-primary-key-column)

If you want to populate a column other than the primary key, set `$randomIdKeyName`:

```
class Invite extends Model
{
    use HasRandomId;

    public $randomIdKeyName = 'token';
}
```

### Customizing the range

[](#customizing-the-range)

The trait exposes two properties you can override per-model:

PropertyDefaultMeaning`$minimumRandomId``3656158440062976`Lower bound. Equals `"10000000000"` parsed as base-36, which guarantees every id is at least 11 characters when rendered in base-36.`$maximumRandomId``9007199254740991`Upper bound. Equals `Number.MAX_SAFE_INTEGER` (2^53 − 1) and fits in MySQL `BIGINT`.```
class Order extends Model
{
    use HasRandomId;

    public $minimumRandomId = 1000000000;
    public $maximumRandomId = 9999999999;
}
```

You can also override `generateRandomInteger()` if you need a different generation strategy entirely.

How it works
------------

[](#how-it-works)

- `bootHasRandomId()` registers a `saving` listener so the id is assigned just before the row is written.
- `initializeHasRandomId()` runs on every model instance and sets `$incrementing = false`.
- `generateRandomInteger()` uses PHP's `random_int()`, which draws from the OS CSPRNG.

Limitations
-----------

[](#limitations)

Random number generation reduces the risk of ID collisions but is not immune to them. The more rows you insert, the higher the chance of a collision due to the [birthday paradox](https://en.wikipedia.org/wiki/Birthday_problem) — random sampling within a finite range (here, 2^53) makes overlap increasingly likely as the table grows. For use cases involving tens of millions of rows or extremely high throughput, consider pre-generating a pool of unique ids and handing them out, or wrapping inserts in retry-on-duplicate-key logic.

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance90

Actively maintained with recent releases

Popularity26

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~681 days

Total

4

Last Release

45d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2696038?v=4)[Michael Slowik](/maintainers/sl0wik)[@sl0wik](https://github.com/sl0wik)

---

Top Contributors

[![sl0wik](https://avatars.githubusercontent.com/u/2696038?v=4)](https://github.com/sl0wik "sl0wik (18 commits)")

---

Tags

randomlaraveluuidfirevel

### Embed Badge

![Health badge](/badges/firevel-model-random-id/health.svg)

```
[![Health](https://phpackages.com/badges/firevel-model-random-id/health.svg)](https://phpackages.com/packages/firevel-model-random-id)
```

###  Alternatives

[webpatser/laravel-uuid

Laravel integration for webpatser/uuid - High-performance drop-in UUID replacements (15% faster than Ramsey). Provides Str macros, HasUuids trait, facades, and casts. RFC 4122/9562 compliant.

1.8k17.9M141](/packages/webpatser-laravel-uuid)[skywarth/chaotic-schedule

Randomize scheduled command execution time and date intervals

12263.8k](/packages/skywarth-chaotic-schedule)[riipandi/laravel-optikey

Use UUID, Ulid, or nanoid as optional or primary key in Laravel.

429.3k](/packages/riipandi-laravel-optikey)[sinergi/token

PHP library to generate random strings

188.9k9](/packages/sinergi-token)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
