Eloquent - use a unique string or a unique int as id

In my table users, Eloquent allows me to use idwith increment:

$table->increments('id');

It's fine. Each new user will receive his id, 1, 2, 3, etc.

However, the identifier must be an automatically assigned string or integer.

I want

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

How can I achieve this with Eloquent?

What I have found so far:

$table->string('id', 36)->primary()
+4
source share
3 answers

.

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

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

ID, .
models/User.php , .

public $incrementing = false;

INT VARCHAR.

+5

, id.

hashid hashid.org

(, YouTube Bitly).

obfuscate · · ·

$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)
}
+4

, .

example.org/user/john

Then, if there are two users with the username john, add a counter to distinguish them.

example.org/user/john-1

End users will not see the identifier. This is a much cleaner way than assigning a random number to each user alias.

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

+2
source

Source: https://habr.com/ru/post/1529188/


All Articles