Я хочу добавить дополнительные условия к запросу аутентификации в дополнение к электронной почте и паролю пользователя в моем проекте Laravel.
Я читал это в официальной документации laravel. https://laravel.com/docs/5.6/authentication
Specifying Additional Conditions If you wish, you may also add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { // The user is active, not suspended, and exists. }
Где я могу найти этот метод?
В вашем LoginController (app / Http / Controllers / Auth / LoginController.php) и аутентифицируйте метод перезаписи. Если он у вас еще есть, выполните: php artisan make: auth






AuthController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller
{
/**
* Handle an authentication attempt.
*
* @return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
Это то, что вы ищете?
Если вы используете scaffolding auth, предоставляемый Laravel, он будет в трейте AuthenticatesUsers:
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
Вы можете переопределить этот метод в своем LoginController.
спасибо, это именно то, что я нашел, я нашел учетные данные функции (запрос $ запрос), которая принимает имя пользователя и пароль, теперь я хочу добавить к нему новый параметр, например, active = 1, Devon
Вам нужно перезаписать логин в вашем LoginController
public function login(\Illuminate\Http\Request $request) {
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
$user = $this->guard()->getLastAttempted();
// Make sure the user is active
if ($user->active && $this->attemptLogin($request)) {
// Send the normal successful login response
return $this->sendLoginResponse($request);
} else {
// Increment the failed login attempts and redirect back to the
// login form with an error message.
$this->incrementLoginAttempts($request);
return redirect()
->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors(['active' => 'You must be active to login.']);
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
Это работает для меня
я проверю
Auth::attempt, которому вы звоните, скорее всего, Illuminate\Auth\SessionGuard@attempt.
Путь:
Auth::attempt -> Illuminate\Auth\AuthManager -> (guard) Illuminate\Auth\SessionGuard
Facade -> Illuminate\Auth\AuthManager@call -> @guard -> Illuminate\Auth\SessionGuard@attempt
Документация Laravel 5.6 - Фасады - Справочник по классам
Чтобы иметь возможность настроить эти учетные данные, переданные для LoginController, вам нужно только переопределить 1 метод, credentials, поскольку это единственный метод, связанный с массивом, который передается в attempt.
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password')
+ ['active' => true];
}
что вы имеете в виду под "Где найти упомянутый метод"? Это тот же метод, к которому вы добавляете дополнительный элемент в массив.