hellicious's avatar

Generate random id from auto increment

so im new in laravel and lumen and im trying to generate random id from my auto increment primary key so everytime someone register it generates random id for my table user_id

how do i do that? thanks in advance

0 likes
7 replies
topvillas's avatar
Level 46
$user = User::create([
    'things' => 'here'
]);

$random = (str) user->id . str_random(10);

$user->field = $random;

$user->save();
Robstar's avatar

If you're keeping the primary key as an integer and simply want to create a random token when a user is being created, I'd advise Observers. See https://laravel.com/docs/5.4/eloquent#observers

You observer class would have a simple method that is fired after the model is created:

public function creating(User $user)
{
    $user->token = str_random(20);
}
hellicious's avatar

@Robstar i tried to use that in lumen but nothing is happen

@topvillas i get this error saying syntax error, unexpected 'user' (T_STRING)

martinbean's avatar

@hellicious Another alternative to UUIDs would be Hashids.

You can create a Hashid from a primary key, and also reverse it by getting the original ID from a Hashid value.

Snapey's avatar

remember if you don't want to use an autoincrementing primary key for eloquent models then you gave to tell eloquent by placing this in your model;

public $incrementing = false;

Please or to participate in this conversation.