1

I'm using laravel 5.4 to develop an api

When trying to login using API Controller

Route::post('/login','Auth\ApiLoginController@login')

class ApiLoginController extends Controller
{
    public function login(Request $request)
    {
        $this->validate($request,[
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);

        /*return response([
            'email' =>$request->email,
            'password'=> $request->password
        ],200);*/

        if(Auth::guard('api')->attempt(['email'=> $request->email, 'password'=> $request->password], $request->remember)){
            //return redirect()->intended(route('admin.dashboard'));
                return response([
                'data' =>"login successfully"
            ], 200);
        }    

        //return redirect()->back()->withInput($request->only('email','remember'));
            return response([
            'data' =>"login failed"
        ],200);
    } 
}

It gives me following error:

{FatalThrowableError Call to undefined method Illuminate\Auth\TokenGuard::attempt()}

1

1 Answer 1

2

In config/auth.php,

change:

'api' => [
    'driver' => 'token',
],

To:

'api' => [
    'driver' => 'session',
],

Because Auth::guard data is stored in the session

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why this is when the API environment typically doesn't (and shouldn't) use sessions at all?
Time pass and we are still facing such a issue with Laravel 10.x To answer you question this is the way Sanctum and Laravel were built, the api auth implementation will use by default the web guard, and this is something that can't be avoided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.