Reputation: 3990
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
How can I achieve this using Eloquent?
What I found so far:
$table->string('id', 36)->primary()
Upvotes: 5
Views: 4397
Reputation: 23962
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
Upvotes: 2
Reputation: 342
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)
}
Upvotes: 4
Reputation: 22862
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.
Upvotes: 5