php - laravel 7 sanctum Hash::check always returns false
Get the solution ↓↓↓I am trying to build laravel auth api with sanctum and I followed the doc but getting this error:
{
"message": "The given data was invalid.",
"errors": {
"data": [
"The provided credentials are incorrect."
]
}
}
Here's the controller:
public function login(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'data' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response($response, 201);
return $user->createToken($request->device_name)->plainTextToken;
}
I found this solution but it returns "true" even if the password is wrong:
Answer
Solution:
Try with this way, usingattempt
$request->validate([
'email' => 'required|email|string',
'password' => 'required|string',
'device_name' => 'required',
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$token = $user->createToken($request->device_name)->plainTextToken;
//return....
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.