Skip to content

firevel/model-random-id

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Model Random ID Generator for Laravel

A package for generating random BIGINT IDs as primary keys in Laravel models. These IDs are compatible with MySQL BIGINT columns and JavaScript's MAX_SAFE_INTEGER.

Purpose

Systems using distributed databases like Cloud Spanner or Firestore shouldn't use incremental id's to avoid bottlenecks. UUID can be used as an alternative but long strings can cause performance issues and UX issues. Random BIGINT is a middle ground between incremental id and UUID.

Installation

Install the package via Composer:

composer require firevel/model-random-id

Usage

Database Setup

Ensure your database table uses a BIGINT primary key. For example:

$table->bigInteger('id')->unsigned()->primary();

Model Setup

Add the trait to your model:

use \Firevel\ModelRandomId\HasRandomId;

Disable auto-incrementing for the primary key:

/**
 * Indicates if the IDs are auto-incrementing.
 *
 * @var bool
 */
public $incrementing = false;

Limitations

While random number generation reduces the risk of ID collisions, it is not entirely immune to conflicts. The more IDs you generate, the higher the chance of a collision due to the Birthday Paradox—where random sampling within a finite range (in this case, BIGINT) increases the likelihood of overlap as the number of samples grows. For use cases involving millions of rows or extremely high throughput, consider pre-generating a list of unique IDs and distributing them to avoid runtime conflicts. This approach ensures scalability while preserving randomness.

About

Model random ID generator for Laravel.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages