fanmade/laravel-nanoid

A small package to add Nano IDs to Laravel

1.0.0 2024-05-14 20:36 UTC

This package is auto-updated.

Last update: 2024-05-14 22:43:20 UTC


README

Laravel Nano ID Logo

Introduction

A simple package to generate Nano IDs in Laravel.

What is a Nano ID?

A Nano ID is a URL-friendly, unique string ID.
It is similar to UUIDs, but shorter and more readable.
Nano IDs are 21 characters long by default and can be customized to be longer or shorter.

Table of Contents

Features

  • A facade to generate Nano IDs
  • A helper function to use as alternative to the facade
  • Configuration options to customize the defaults for your Nano IDs
    • Prefix
    • Suffix
    • Alphabet
    • Size
    • Random string generator
    • More to come
  • Easily extensible with custom validation rules (like uniqueness or swear word checks)

Requirements

  • PHP >= 8.0

Installation

composer require fanmade/laravel-nanoid

Usage

use Fanmade\NanoId\Facades\NanoID;

echo NanoID::generate(); // Returns a Nano ID

echo NanoID::generate(length: 10); // Returns a Nano ID with a length of 10

echo NanoID::generate(length: 10, prefix: 'prefix_'); // Returns a Nano ID with a length of 10 and a prefix of 'prefix_'

echo NanoID::generate(suffix: '_suffix'); // Returns a Nano ID with a suffix of '_suffix'

echo NanoID::generate(alphabet: '0123456789'); // Returns a Nano ID only containing numbers

echo nano_id(); // The helper function accepts the same parameters as the generate method

Configuration

Publish the configuration file

php artisan vendor:publish --tag=nanoid-config
Option Description Default
prefix An optional prefix which will be added to the Nano ID ''
suffix An optional suffix which will be added to the Nano ID ''
alphabet The alphabet to use for generating the Nano ID 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_+
abcdefghijklmnopqrstuvwxyz-
size The default size/length of the Nano ID 21
generator The generator class to use for generating random strings \Fanmade\NanoId\Generator\HidehaloStringGenerator
include_prefix_in_length Controls if the prefix is included or excluded in the size limitation true
include_suffix_in_length Controls if the suffix is included or excluded in the size limitation true

Testing

vendor/bin/pest

or

composer test

Alternatives (and inspirations)