skip to Main Content

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


  1. Login attempt doesnt work. Because You should save password with HASH.

    You should encrypt password before store the user in DB.

    $data = $request->validated();
    $data['password'] = Hash::make($request->get('password'));
    $user = User::create($data);
    

    But will be better to use Auth::login($user) method instead of Auth::attempt().

    Login or Signup to reply.
  2. tries to use the same object created at that moment:

    $user = User::create($data);
    
    Auth::login($user);
    
    return response()->json([
                'status' => 'success',
                'username' => $user->username,
                'token' => $user->createToken($request->username)->plainTextToken,
            ], 201);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search