Create token while registering a user in laravel
Posted 5 years ago by Ryan Dhungel
Category: Laravel
Viewed 7005 times
Estimated read time: 1 minute
How to create a token with a random numbers for a user and save in the database while registering a new user in laravel?
With token field in the database and eloquent relationship between user and token model, you can use the following code to generate a random numbers for each user while registering them.
In App/Http/Controllers/Auth/AuthController.php
, modify the create method to the following:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->token()->create([
'token' => str_random(255)
]);
return $user;
}