Laravel API | Login Validation

6 hari yang lalu  |  43x dilihat
<?php 
// Laravel API | Login Validation

public function userLogin(Request $request)
{
	try {
	$userValidation = Validator::make($request->all(), 
	[
	'username' => 'required',
	'password' => 'required',
	'code' => 'required'
	]);

	if ($userValidation->fails()){
	return response()->json([
	'status' => false,
	'message' => 'Validation error',
	'errors' => $userValidation->errors()
	], 401);
	}

	if (!Auth::attempt($request->only(['username', 'password', 'code']))){
	return response()->json([
	'status' => false,
	'message' => 'Invalid credentials',
	], 401);
	}

	$user = User::where('username', $request->username)->first();

	return response()->json([
	'status' => true,
	'message' => 'You are now logged in',
	'token' => $user->createToken("jwt_token")->plainTextToken
	], 200);

	} catch (\Throwable $th) {
	return response()->json([
	'status' => false,
	'message' => $th->getMessage()
	], 500);
	}
}