I used Laravel-Passport for my Laravel 5.8 Authentication for my api endpoint
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Validator;
public function login(Request $request)
{
$validator = Validator::make($request->all('email', 'password'), [
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
};
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], 200);
}
else{
return response()->json(['error'=>'Can not log in with the data provide.'], 401);
}
}
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
When I tested the endpoint on POSTMAN, I got this error:
What is the cause of the error, and how do I resolve it?
BadMethodCallException Method Illuminate\Auth\RequestGuard::attempt does not exist.
To log a user in with a username and password you need to use your web
authentication guard like this:
if(Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::guard('web')->user();
I had this same issue when testing routes I recently added. Clearing the cached routes fixed this for me:
php artisan route:clear
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With