user11352561
user11352561

Reputation: 2647

Laravel - Method Illuminate\Auth\RequestGuard::attempt does not exist when testing the api

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:

postman_error

What is the cause of the error, and how do I resolve it?

BadMethodCallException Method Illuminate\Auth\RequestGuard::attempt does not exist.

Upvotes: 4

Views: 12908

Answers (3)

Mhmd
Mhmd

Reputation: 476

I had same problem with Laravel Nova,

I went to config/auth.php and changed default guard to web :

    'defaults' => [
    'guard' => 'api', ===> change this to web
    'passwords' => 'users',
],

Upvotes: 0

Zach Vander Velden
Zach Vander Velden

Reputation: 21

I had this same issue when testing routes I recently added. Clearing the cached routes fixed this for me:

php artisan route:clear

Upvotes: 2

D Malan
D Malan

Reputation: 11424

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();

Upvotes: 8

Related Questions