Laravel 5.6登录尝试失败-登录提交时返回方法RequestGuard :: attempt不存在 [英] Laravel 5.6 Login Attempt Fails - Method RequestGuard::attempt does not exist is returned on Login Submit

查看:513
本文介绍了Laravel 5.6登录尝试失败-登录提交时返回方法RequestGuard :: attempt不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为我的应用程序实现了多重身份验证,并且在停止之前一切正常,我一直在互联网上寻找解决方案,但无济于事.因此,我确实拥有管理员登录控制器和默认的Laravel登录控制器,该控制器使用make:auth并为用户实现了可验证性.我的管理员登录正常,但用户登录失败并返回此

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

当我尝试注册用户时也会发生同样的事情,但是这次返回它会返回

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

尽管用户注册通过时出错,但实际上是从注册表单在用户表中填充了这些字段.由于我使用的是默认身份验证,因此我希望它能够自动登录,并且我猜这是attemp方法出现问题的地方.

当务之急是要在另一个模块的用户模型上使用Passport.

下面是我的登录控制器的外观

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

}

和我的管理员登录控制器

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'admin/dashboard';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.admin-login');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    public function login(Request $request)
    {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:8'
        ]);
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
        }
        // if unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->with('flash_message_error', 'Invalid Access: Please Login With Your Credentials.');
    }
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('admin')->with('flash_message_error', 'Successfully Logged Out');;
    }

}

这是我的警卫config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 15,
        ],
    ],

];

最后是我的用户模型

namespace App;

use App\Modules\Event\Bookings;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use GrahamCampbell\Markdown\Facades\Markdown;

/**
 * @method static find($user_id)
 * @method static count()
 */
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname','lname', 'email','organization','phone_number', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',

    ];

    public function participant()
    {
        return $this->hasMany(Bookings::class);
    }


    public function posts()
    {
        return $this->hasMany(Posts::class, 'author_id');
    }
    public function gravatar()
    {
        $email = $this->email;
        $default = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/User_icon-cp.svg/200px-User_icon-cp.svg.png";
        $size = 60;

        return "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;
    }
        public function getRouteKeyName()
    {
        return 'slug';
    }
    public function getBioHtmlAttribute()
    {
        return $this->bio ? Markdown::convertToHtml(e($this->bio)) : NULL ;

    }

}

下面是我的管理员模型

namespace App;


use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * @method static find($user_id)
 */
class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';
    /**
     * 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',

    ];


}

我尝试使用api作为默认防护,它只能临时工作并开始返回相同的错误,我知道try方法仅适用于Web中间件,所以可能是什么问题?我已经删除了供应商文件夹,并使用composer update重新安装了它...只是卡住了. 非常感谢您的帮助.

解决方案

为了回答这个问题,我绞尽脑汁后,决定清除应用程序,配置和路由缓存,这对我来说是成功的秘诀.

>

php artisan cache:clear

当您希望清除应用程序缓存时,可以在控制台中运行以上语句.它的作用是清除了存储\ framework \ cache中的所有缓存.

php artisan route:cache

这将清除您的路由缓存.因此,如果您添加了一条新路线或更改了路线控制器或动作,则可以使用此路线来重新加载它.

php artisan config:cache

这将清除env文件的缓存并重新加载

最后您可以运行

composer dump-autoload -o

Composer dump-autoload不会下载任何东西. 它只是重新生成需要包含在项目中的所有类的列表(autoload_classmap.php).

I had implemented multi-auth for my application and it was working fine until it just stopped.I've scoured the internet for a solution but to no avail. So I do have Admin Login Controller and the default Laravel Login controller which uses make:auth and implements authenticable for users. My admin login is working fine but the user login fails and returns this

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

The same thing happens when I try to register a user but this time it returns it returns

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

Despite the error the user registration passes and the fields are actually populated in the users table from the registration form. Since I'm using the default auth I'm expecting it to automatically login , and i guess this is where the problem arises on the attemp method.

It's imperative to note that I am using Passport on the user Model for another module.

Below is how my Login Controller looks like

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

}

And my Admin Login Controller

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'admin/dashboard';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.admin-login');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    public function login(Request $request)
    {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:8'
        ]);
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
        }
        // if unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->with('flash_message_error', 'Invalid Access: Please Login With Your Credentials.');
    }
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('admin')->with('flash_message_error', 'Successfully Logged Out');;
    }

}

This is my guard config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 15,
        ],
    ],

];

And finally below is my user Model

namespace App;

use App\Modules\Event\Bookings;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use GrahamCampbell\Markdown\Facades\Markdown;

/**
 * @method static find($user_id)
 * @method static count()
 */
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname','lname', 'email','organization','phone_number', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',

    ];

    public function participant()
    {
        return $this->hasMany(Bookings::class);
    }


    public function posts()
    {
        return $this->hasMany(Posts::class, 'author_id');
    }
    public function gravatar()
    {
        $email = $this->email;
        $default = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/User_icon-cp.svg/200px-User_icon-cp.svg.png";
        $size = 60;

        return "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;
    }
        public function getRouteKeyName()
    {
        return 'slug';
    }
    public function getBioHtmlAttribute()
    {
        return $this->bio ? Markdown::convertToHtml(e($this->bio)) : NULL ;

    }

}

Below is My Admin Model

namespace App;


use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * @method static find($user_id)
 */
class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';
    /**
     * 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',

    ];


}

I tried to use api as the default guard and it only worked temporarily and started to return the same error, I know attempt method only works on web middleware so what could be the problem? I've removed the vendor folder and reinstalled it using composer update still nothing.. just stuck. Would immensly appraciate the help.

解决方案

So to answer this question, after racking my brain, I decided to clear the application, configuration, and route caches,that did the trick for me.

php artisan cache:clear

You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.

php artisan route:cache

This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.

php artisan config:cache

This will clear the caching of the env file and reload it

Finally you can run

composer dump-autoload -o

Composer dump-autoload won’t download a thing. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).

这篇关于Laravel 5.6登录尝试失败-登录提交时返回方法RequestGuard :: attempt不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆