Categories: Development

How to have a random string for user id in Laravel

How to have randomly generated strings as user ids in Laravel instead of incrementing integers.

By having random strings for identification you can avoid revealing how many users you have, and avoid having predictability with ids.

This is a simple change to implement, you only need to modify 3 files:

  1. create_users_table.php migration file
  2. app/Models/User.php
  3. app/Http/Controllers/Auth/RegisterController.php

In the create_users_table.php migration file, change the id column to be a CHAR 8, primary key. CHAR is fixed length, in this case every value in this column will have a length of 8

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->char('id',8)->primary();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

In app/Models/User.php set incrementing as false and make sure you have id in fillable as we will be assigning/inserting an id value manually

public $incrementing = false;

protected $fillable = ['id','name','email','password'];

Next, add the following function, this will generate a random 8 character string for the id and ensure it hasn’t been assigned already.

public static function generateUserid(int $length = 8): string
{
    $user_id = Str::random($length);//Generate random string

    $exists = DB::table('users')
        ->where('id', '=', $user_id)
        ->get(['id']);//Find matches for id = generated id

    if (isset($exists[0]->id)) {//id exists in users table
        return self::generateUserid();//Retry with another generated id
    }

    return $user_id;//Return the generated id as it does not exist in the DB
}

The random string is generated with Illuminate\Support\Str random().

It will be very very rare to come across a duplicate string doing a random length of 8.

Next in app/Http/Controllers/Auth/RegisterController.php ensure in the create function the id has the generateUserid function from above.

protected function create(array $data)
{
    return User::create([
        'id' => User::generateUserid(),
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

That is all, your users when registering will now be assigned random 8 character strings for ids instead of auto-incrementing integers. You can follow this process for ids of other tables too.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago