FareedR
6 months ago

What should i response in login process ?

Posted 6 months ago by FareedR

I'm doing API right now . what should i response if user exist and has that role because if in web, we just redirect it to folder . how about in API ? should do the same thing or just return response success ? p/s first time developing an API

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'id_no' => 'required|string',
            'password' => 'required|string'
        ]);

        $credentials = request(['id_no','password']);

        // Check credentials
        if(!Auth::attempt($credentials)){
            return response()->json([
                'message' => 'Unauthorized'
            ],401);
        }else{
            $user = $request->user();

            // Create user token
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->save();
            
            if($user->hasRole('student')){
                return response()->json([
                    'access_token' => $tokenResult->accessToken,
                    'token_type' => 'Bearer',
                    'user' => $user
                ],201);
            }
        }
    }
}

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