Create token while registering a user in laravel


Posted 7 months ago by Ryan Dhungel

Category: Laravel

Viewed 1160 times

Estimated read time: 1 minute

Course of the day!

Laravel with Nuxt JS - Build API Driven SSR Vue JS Web Application

Laravel with Nuxt JS - Build API Driven SSR Vue JS Web Application

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;
}