Martin1182
3 months ago
463
5
Laravel

API TOKEN

Posted 3 months ago by Martin1182

Good day. When registering a user in the register controller, I would like to call the update function in apiTokenController to automatically create an api_token and save this token in the DB. I want to do this so that the user has api_token assigned to him after registration so that he does not have to request it manually. What is the best way? Well thank you.

protected function create(array $data) {

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}

public function update(Request $ request) {

    $token = Str::random(60);

    $request->user()->forceFill([
        'api_token' => hash('sha256', $token),
    ])->save();

    return ['token' => $token];
}

Please sign in or create an account to participate in this conversation.