laravel - 为ip定义常量以便不调用函数

时间:2017-10-03 16:51:40

标签: laravel ip constants

我想调用函数$ request-> ip()一次并将ip放在一个常量中,以便每次都不需要调用该函数。因此,由于未在页面中调用函数10次,资源使用量会减少,而只能回显从该函数中提取的已定义常量一次。

Laravel有可能吗?如果是的话怎么样?

2 个答案:

答案 0 :(得分:0)

您可以使用Sessions

覆盖login()中的LoginController方法并添加以下内容:

if(!\Session::has('user_ip'))
            \Session::put('user_ip',$request->ip());

完整方法:

 /**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function login(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);
    }

    if ($this->attemptLogin($request)) {
        if(!\Session::has('user_ip'))
            \Session::put('user_ip',$request->ip());
        return $this->sendLoginResponse($request);
    }

    // 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);
}

请记住导入\ Illuminate \ Http \ Request:

use Illuminate\Http\Request;

现在你可以在任何地方使用Session::get('user_ip')

答案 1 :(得分:0)

我不相信呼叫$request->ip()比调用会话甚至常量更多地使用资源。

使用$_SERVER超全局的任何php请求始终可以访问IP,$request->ip()只是一个包装器。