Я реализовал multi-auth для своего приложения, и оно работало нормально, пока оно просто не остановилось. Я искал в Интернете решение, но безрезультатно.Таким образом, у меня есть Admin Login Controller и контроллер входа Laravel по умолчанию, который использует make: auth и реализует аутентификацию для пользователей.Моя учетная запись администратора работает нормально, но вход пользователя не удается и возвращает это
BadMethodCallException Method Illuminate\Auth\RequestGuard::attempt does not exist.
То же самое происходит, когда я пытаюсь зарегистрировать пользователя, но на этот раз он возвращает, возвращает
BadMethodCallException
Method Illuminate\Auth\RequestGuard::login does not exist.
Несмотря на ошибку, регистрация пользователя проходит, и поля фактически заполняются в таблице пользователей из формы регистрации.Так как я использую аутентификацию по умолчанию, я ожидаю, что он автоматически войдет в систему, и я предполагаю, что именно здесь возникает проблема с методом попытки.
Необходимо отметить, что я использую 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 в качестве защиты по умолчанию, и этотолько временно работал и начал возвращать ту же ошибку, я знаю, что метод попытки работает только на веб-промежуточном программном обеспечении, так в чем может быть проблема?Я удалил папку вендора и переустановил ее, используя обновление композитора, но ничего ... просто застрял.Безмерно оценил бы помощь.