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.

Larave random strings as user id

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) {

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.