cbenjafield / laravel-nano-ids
A Laravel package for adding Nano ID support to a Laravel application.
v0.0.1
2025-08-18 11:17 UTC
Requires
- php: ^8.4
- hidehalo/nanoid-php: ^2.0
- illuminate/support: ^12.0
Requires (Dev)
- laravel/pint: ^1.17
- orchestra/testbench: ^10.4
- pestphp/pest: ^3.0
- pestphp/pest-plugin-laravel: ^3.0
README
Attach Nano IDs to Laravel models using the hidehalo/nanoid-php package.
Installation
composer require cbenjafield/laravel-nano-ids
Configuration
The package will work out of the box, but if you want to publish the configuration file, you can run:
php artisan vendor:publish --provider="Cbenjafield\LaravelNanoIds\NanoIdServiceProvider"
This will create a config/nanoid.php
file where you can customise the default settings for Nano IDs, such as the mode and size.
Usage
Model Setup
Attach the HasNanoId
trait to a model:
use Cbenjafield\LaravelNanoIds\HasNanoId; // Optional: specify a custom length for the Nano ID protected function getNanoIdSize(): int { return 16; // Default is 21 }
By default the model's primary key field ('id') will be used for the Nano ID. If you want to use a different field, you can use Laravel's $primaryKey
properties:
use Illuminate\Database\Eloquent\Model; use Cbenjafield\LaravelNanoIds\HasNanoId; class MyModel extends Model { use HasNanoId; protected $primaryKey = 'custom_id'; // Use 'custom_id' instead of 'id' }
Migrations
When creating a migration for a model that uses Nano IDs, you can use the nanoId
and primaryNanoId
methods to define the columns:
use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; public function up() { Schema::create('my_models', function (Blueprint $table) { $table->primaryNanoId('custom_id'); // Creates a primary key with Nano ID $table->nanoId('another_nano_id'); // Creates a regular Nano ID column $table->nanoId('nano_id_with_length', 16); // Creates a Nano ID with a custom length $table->string('name'); $table->timestamps(); }); }