Home » Php » Eloquent – use unique string or unique int as id

Eloquent – use unique string or unique int as id

Posted by: admin November 30, 2017 Leave a comment

Questions:

For my users table, Eloquent lets me use an id with increment:

$table->increments('id');

That is just fine. Every new user will get their id, 1, 2, 3, etc.

However the id should be an automatically assigned string or integer.

I want

  • the user not to know how many users there are
  • the user
    id to be like at least 5 digits (47533) or be a unique random string (f8hrcrft13)

How can I achieve this using Eloquent?

What I found so far:

$table->string('id', 36)->primary()
Answers:

You can assign ID while creating user model.

$data = [
    'id' => str_random(10),
    'first_name' => 'Andrej'
];

$user = User::create($data);

However, this will ignore ID you specify by default.
You need to edit models/User.php a bit and tell you do not want auto incrementing.
Add this property at the top

public $incrementing = false;

Do not forget to change column type in users table from INT to VARCHAR.

Questions:
Answers:

dont change your database structure, incrementation of id is important to prevent error duplicate.

just using hashid hashid.org

Generate short hashes from numbers (like YouTube and Bitly).

obfuscate database IDs · use them as forgotten password hashes · invitation codes · store shard numbers

$hashids = new Hashids\Hashids('this is my salt');
$hash = $hashids->encrypt(1, 2, 3);
$numbers = $hashids->decrypt($hash);

var_dump($hash, $numbers);

return :

string(5) "laUqtq"

array(3) {
   [0]=>
   int(1)
   [1]=>
   int(2)
   [2]=>
   int(3)
}

Questions:
Answers:

Make a slug for each user with its username e.g.

example.org/user/john

Then if there are two users with john username append a counter to differentiate them.

example.org/user/john-1

Endusers won’t see any id. This is a much cleaner way than assigning a random number to each User alias.

You can do this easily with https://github.com/cviebrock/eloquent-sluggable

Leave a Reply

Your email address will not be published. Required fields are marked *