I am trying multiguard authentication for api when i login for admin i am getting following error
BadMethodCallException Method Illuminate\Auth\Req uestGuard::attempt does not exist.
here is my login method in controller
public function login(Request $request){
if(Auth::guard('admin-api')->attempt(['email' => request('email'), 'password' => request('password')]))
{
// if successful, then redirect to their intended location
$user = Auth::guard('admin-api');
$success['token'] = $user->createToken('admin')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
my api.php
Route::prefix('admin')->group(function () {
Route::post('login', 'API\Admin\AdminController@login')->name('admin.login');
Route::post('register', 'API\Admin\AdminController@register')->name('admin.register');
Route::group(['middleware' => 'auth:admin-api'], function(){
Route::post('get-details', 'API\Admin\AdminController@getDetails');
});
});
my admin model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $table = 'admin';
protected $guard = 'admin-api';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
please tell me any other inputs you want
A better hack is this
$credentials = ['email' => $request->username, 'password' => $request->password];
//Since we are not using guard web in API request, we have to add it here (
// guard('web') ) to access the Auth::attempt function,
// the Auth::attempt needs web guard and crsf token, but using it here bypasses
// the post with crsf.
if (Auth::guard('web')->attempt($credentials, false, false)) {
dd('user is OK');
}else{
dd('user is NOT OK');
}
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