RequestGuard::attempt does not exist

11,013

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');
    }
Share:
11,013
Pranav Mandlik
Author by

Pranav Mandlik

Passionate and enthusiastic laravel developer, have learned a lot from stack overflow, thanks for that, always got answer from stack overflow

Updated on June 04, 2022

Comments

  • Pranav Mandlik
    Pranav Mandlik almost 2 years

    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