Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent - use unique string or unique int as id

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()
like image 725
Shlomo Avatar asked Feb 27 '14 10:02

Shlomo


3 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.

like image 74
Andreyco Avatar answered Sep 20 '22 21:09

Andreyco


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)
}
like image 27
dhidy Avatar answered Sep 24 '22 21:09

dhidy


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

like image 38
marcanuy Avatar answered Sep 22 '22 21:09

marcanuy