AuthController
namespace AppHttpControllersApi;
use AppHttpControllersController;
use AppModelsUser;
use AppHttpRequestsApiRegisterRequest;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
class AuthController extends Controller
{
public function signUp(RegisterRequest $request)
{
$data = $request->validated();
$user = User::create($data);
Auth::attempt(['username'=>$data['username'], 'password'=>$data['password']]);
$token = auth()->user()->createToken($data['username']);
return response([
'status' => 'success',
'username' => $user->username,
'token' => $token->plainTextToken,
], 201);
}
Router
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersApiAuthController;
Route::post('/signup', [AuthController::class, 'signUp'])->name('auth.signup');
When I send a request in postman to this url http://127.0.0.1:8000/api/v1/signup I get an error Call to a member function createToken() on null in file D:OpenServerdomainslocalhostdemoAapp HttpControllersApiAuthController.php on line 18
I tried to install Sanctum, but because I’m new, I don’t know if I did it right
2
Answers
Login attempt doesnt work. Because You should save password with HASH.
You should encrypt password before store the user in DB.
But will be better to use
Auth::login($user)
method instead ofAuth::attempt()
.tries to use the same object created at that moment: