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:
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.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…