Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
user11352561 Avatar asked Jan 01 '23 17:01

user11352561


2 Answers

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();
like image 152
D Malan Avatar answered Jan 05 '23 11:01

D Malan


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

php artisan route:clear
like image 45
Zach Vander Velden Avatar answered Jan 05 '23 10:01

Zach Vander Velden