5

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()
Shlomo
  • 3,880
  • 8
  • 50
  • 82

3 Answers3

5

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.

Andreyco
  • 22,476
  • 5
  • 61
  • 65
  • Did you mean to set `$incrementing` to `true`? – Phill Sparks Feb 27 '14 at 10:51
  • 1
    Thanks. What is `str_random`? Cannot find it in PHP or Laravel. Own impl? Im looking for a built-in functionality to ensure my random id is unique. – Shlomo Feb 27 '14 at 11:45
  • 1
    `str_random` is Laravel helper function http://laravel.com/docs/helpers#strings You need to check on your own to see if ID is unique. – Andreyco Feb 27 '14 at 12:00
4

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)
}
Community
  • 1
  • 1
dhidy
  • 342
  • 1
  • 3
  • 10
  • Thanks I will take a look at hasids. So would you use the incrementing id and an additional userid generated with hashids? – Shlomo Feb 27 '14 at 11:42
2

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

marcanuy
  • 23,118
  • 9
  • 64
  • 113