Use Nanoids within your laravel application.

Overview

Laravel Nanoid

Introduction

A simple drop-in solution for providing nanoid support for the IDs of your Eloquent models. (Stripe-like IDs)

Installing

composer require malico/laravel-nanoid

Usage

There are two ways to use this package:

  • By extending the provided model classes (preferred and simplest method).
  • By using the provided model trait (allows for extending another model class).

Extend the model classes

While creating your model, you can extend the Eloquent Model class provided by the package.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Malico\LaravelNanoid\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
}

To create model fast and easy, use the artisan command make:nanoid-model, same as you will do with the make:model command. All arguments work the same as the make:model command. To create migration file with string id (which is what is needed), add the -m option, the migration file created will have id of string type (string) instead of autoincrementing integer type.

Extend the model trait

With the ModelTrait trait, all you need to do is add the trait to your model class, then make you sure model properties look like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
namespace Malico\LaravelNanoid\Eloquent\InteractsWithNanoid;

class Book extends Model{
    use HasFactory;
    use InteractsWithNanoid;

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

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The "booting" method of the model.
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (self $model): void {
            $model->{$model->getKeyName()} = $model->generateNanoid();
        });
    }
}

Take note of the $incrementing and $keyType properties. Also make sure within your boot method you call the parent::boot method and then add the creating event listener. Also make sure your id column is set to string type.

// migration file
public function up()
{
    Schema::create('test_models', function (Blueprint $table) {
        $table->string('id')->primary();
        //
        $table->timestamps();
    });
}

To create a new migration, use the artisan command make:nanoid-migration. All arguments work the same as the make:migration command.

Options

  1. Prefix: To Specify a Prefix for the IDs, you can specify a prefix by add `nanoPrefix' property to your model class.
  2. Same applies for the length of the ID.
<?php

    /**
     * Nano id length.
     *
     * @var array|int
     */
    protected $nanoidLength = 10;
    // id will be of length 10
    // specifying to array. e.g [10, 20] will generate id of length 10 to 20

    /**
     * Nano id prefix.
     *
     * @var string
     */
    protected $nanoidPrefix = 'pl_'; // id will look: pl_2k1MzOO2shfwow ...

This is inspired by the Laravel Eloquent UUID package and stripe's transaction ids.

If you want to customize the user model, Replace the follows namespace in your user model.

// use Illuminate\Foundation\Auth\User as Authenticatable;
use Malico\LaravelNanoid\Auth\User as Authenticatable;

#class User extends Authenticatable

Author

Ndifon Desmond Yong

You might also like...
Automatically load your helpers in your laravel application.

Laravel AutoHelpers Automatically load your helpers in your laravel application. Installation You can install the package via composer: composer requi

Laravel-veneer - A suite of mocked services to use in your Laravel tests.

Laravel Veneer A suite of fixture data and methods to help make mocking 3rd party services easier. Overview Laravel Veneer aims to solve two problems

A package to easily make use of Iconic icons in your Laravel Blade views.
A package to easily make use of Iconic icons in your Laravel Blade views.

Blade Iconic A package to easily make use of Iconic icons in your Laravel Blade views. For a full list of available icons see the SVG directory. Iconi

A package to easily make use of Simple Icons in your Laravel Blade views.
A package to easily make use of Simple Icons in your Laravel Blade views.

Blade Simple Icons A package to easily make use of Simple Icons in your Laravel Blade views. For a full list of available icons see the SVG directory.

Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework.
Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework.

Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework. This rep

Zarinpal is a laravel package to easily use zarinpal.com payment services in your applications
Zarinpal is a laravel package to easily use zarinpal.com payment services in your applications

پکیج اتصال به درگاه پرداخت زرین پال zarinpal.com برای اتصال به درگاه پرداخت اینترنتی زرین پال و استفاده از api های آن می توانید از این پکیج استفاده کن

Use Kafka Producers and Consumers in your laravel app with ease!
Use Kafka Producers and Consumers in your laravel app with ease!

Laravel Kafka Do you use Kafka in your laravel packages? All packages I've seen until today, including some built by myself, does not provide a nice s

Cagilo - a set of simple components for use in your views Laravel Blade.

Cagilo - a set of simple components for use in your views Laravel Blade. Official Documentation Documentation for Cagilo can be found on its we

🛂 Use this package to validate the identity card from your country using laravel validation rules.

Identity Card Checker Laravel Validation Rules Use this package to validate the identity card number from your country Installation You can install th

Comments
  • Add support for laravel 9.0

    Add support for laravel 9.0

    Update to Laravel 9.0 fails.

    - malico/laravel-nanoid 0.2.1 requires illuminate/auth ^8.0 -> satisfiable by illuminate/auth[v8.0.0, ..., 8.x-dev].
    - Root composer.json requires malico/laravel-nanoid ^0.2.1 -> satisfiable by malico/laravel-nanoid[0.2.1].
    - Root composer.json requires laravel/framework ^9.0 -> satisfiable by laravel/framework[v9.0.0-beta.1, ..., 9.x-dev].
    
    opened by dusanbre 0
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • composer.json (composer)

    Configuration

    🔡 Renovate has detected a custom config for this PR. Feel free to ask for help if you have any doubts and would like it reviewed.

    Important: Now that this branch is edited, Renovate can't rebase it from the base branch any more. If you make changes to the base branch that could impact this onboarding PR, please merge them manually.

    What to Expect

    With your current configuration, Renovate will create 1 Pull Request:

    Pin dependencies

    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
Releases(0.3.0)
Owner
Malico
Geeking away.
Malico
Manage meta data based on URL path within your app.

Laravel SEO Manager This package provides simple functionality to manage SEO tags based on URL path within your Laravel application. You can put the U

Michael Rubel 20 Oct 20, 2022
A simple way to add 301/302 redirects within CraftCMS.

Redirector plugin for Craft CMS 3.x A simple way to add 301/302 redirects within CraftCMS. This is the first CraftCMS plugin written by myself so plea

Jae Toole 1 Nov 25, 2021
Textpattern-jquery-ui-theme - The jQuery UI theme used within the Textpattern CMS admin-side.

Textpattern jQuery UI theme The jQuery UI theme used within the Textpattern CMS admin-side. Supported web browsers Chrome, Edge, Firefox, Safari and O

Textpattern CMS 12 Jan 10, 2022
Collection of classes you can use to standardize data formats in your Laravel application.

Laravel Formatters This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Co

Michael Rubel 88 Dec 23, 2022
A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.

QueryBuilderParser Status Label Status Value Build Insights Code Climate Test Coverage QueryBuilderParser is designed mainly to be used inside Laravel

Tim Groeneveld 149 Nov 11, 2022
A Laravel package that allows you to use multiple ".env" files in a precedent manner. Use ".env" files per domain (multi-tentant)!

Laravel Multi ENVs Use multiple .envs files and have a chain of precedence for the environment variables in these different .envs files. Use the .env

Allyson Silva 48 Dec 29, 2022
A Laravel chat package. You can use this package to create a chat/messaging Laravel application.

Chat Create a Chat application for your multiple Models Table of Contents Click to expand Introduction Installation Usage Adding the ability to partic

Tinashe Musonza 931 Dec 24, 2022
A super simple package allowing for use MySQL 'USE INDEX' and 'FORCE INDEX' statements.

Laravel MySQL Use Index Scope A super simple package allowing for use MySQL USE INDEX and FORCE INDEX statements. Requirements PHP ^7.4 | ^8.0 Laravel

Vasyl 29 Dec 27, 2022
Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

Laravel Eloquent Scope as Select Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes an

Protone Media 75 Dec 7, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022