Laravel Auth :: check () всегда подключается к БД для проверки пользователя? - PullRequest
0 голосов
/ 20 февраля 2020

Я использую Auth::check() для проверки статуса входа пользователя.

Подключается ли Auth::check() к базе данных для каждой проверки входа в систему?

Ответы [ 3 ]

0 голосов
/ 20 февраля 2020

Метод check() делает это:

/**
 * Determine if the current user is authenticated.
 *
 * @return bool
 */
public function check()
{
    return ! is_null($this->user());
}

Теперь интересная часть - то, что делает метод user(). Вы можете увидеть это подробно и подробно объяснить в исходном коде :

public function user()
{
    if ($this->loggedOut) {
        return;
    }

    // If we've already retrieved the user for the current request we can just
    // return it back immediately. We do not want to fetch the user data on
    // every call to this method because that would be tremendously slow.
    if (! is_null($this->user)) {
        return $this->user;
    }

    $id = $this->session->get($this->getName());

    // First we will try to load the user using the identifier in the session if
    // one exists. Otherwise we will check for a "remember me" cookie in this
    // request, and if one exists, attempt to retrieve the user using that.
    if (! is_null($id) && $this->user = $this->provider->retrieveById($id)) {
        $this->fireAuthenticatedEvent($this->user);
    }

    // If the user is null, but we decrypt a "recaller" cookie we can attempt to
    // pull the user data on that cookie which serves as a remember cookie on
    // the application. Once we have a user we can return it to the caller.
    if (is_null($this->user) && ! is_null($recaller = $this->recaller())) {
        $this->user = $this->userFromRecaller($recaller);

        if ($this->user) {
            $this->updateSession($this->user->getAuthIdentifier());

            $this->fireLoginEvent($this->user, true);
        }
    }

    return $this->user;
}
0 голосов
/ 20 февраля 2020

Вместо RequestGuard защита по умолчанию - SessionGuard. И да, при первом вызове Auth::check() будет выполнен один поиск в базе данных для проверки текущего пользователя, вошедшего в систему.

После этого каждый последующий вызов в том же запросе не будет выполнять другой поиск в базе данных.

0 голосов
/ 20 февраля 2020

Auth::check() проверяет, что текущий сеанс имеет аутентифицированного пользователя, либо уже проверенного, либо из сеанса (который будет использовать БД в первый раз) или нулевого значения.

Illuminate \ Auth \ GuardHelpers. php

**
     * Determine if the current user is authenticated.
     *
     * @return bool
     */
    public function check()
    {
        return ! is_null($this->user());
    }

Пример @ Подсветка \ Auth \ RequestGuard. php

/**
     * Get the currently authenticated user.
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function user()
    {
        // If we've already retrieved the user for the current request we can just
        // return it back immediately. We do not want to fetch the user data on
        // every call to this method because that would be tremendously slow.
        if (! is_null($this->user)) {
            return $this->user;
        }

        return $this->user = call_user_func(
            $this->callback, $this->request, $this->getProvider()
        );
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...