【问题标题】:any big differ between $user->getAuthPassword() and Auth::user()->password? laravel 4$user->getAuthPassword() 和 Auth::user()->password 之间有什么大的不同吗?拉拉维尔 4
【发布时间】:2014-03-06 10:59:57
【问题描述】:

我在网上学习这个登录教程,用户登录后可以选择更改密码,并且给出的注释是

if ($validator->fails())
{
    return Redirect::route('account-change-password')
        ->withErrors($validator);
}
else
{
    $user = User::find(Auth::user()->id);

    $old_password = Input::get('old_password');
    $password = Input::get('password');

    if(Hash::check($old_password, $user->getAuthPassword()))
    {
        $user->password = Hash::make($password);

        if($user->save())
        {
            return Redirect::route('home')
                ->with('global', 'Your Password has been changed');
        }
    }
    else
    {
        return Redirect::route('account-change-password')
            ->with('global', 'Your old password is incorrect');
    }
}

在教程里面的else $user = User::find(Auth::user()->id);被立即使用,然后检查密码的if语句使用$user = User::find(Auth::user()->id);

当我在观看教程后尝试在我的 on 上执行此操作时,我的做法有所不同。

if ($v->fails())
{
    return Redirect::route('account-change-password')
        ->withErrors($v)
        ->with('global', 'Please check the errors in red');
}
else
{
    if (Hash::check(Input::get('old_password'),Auth::user()->password))
    {
        $user = User::find(Auth::user()->id);
        $user->password = Hash::make(Input::get('new_password'));
        if ($user->save())
        {
            return Redirect::route('home')
                ->with('global', 'Password Changed.');
        }
    }
    return Redirect::route('account-change-password')
            ->with('global', 'Old password is incorrect');
}

我使用 if 语句立即使用 Auth::user()->password) 检查了密码和数据库中的密码,并将 $user = User::find(Auth::user()->id); 放入 if 语句中,以便我可以访问 $user->password 并更改密码。

我知道做事总是有很多不同的方法,但我只是想知道我这样做的方式将来是否会出现某种我现在没有意识到的问题,最好记住并坚持教程教的方式。

【问题讨论】:

    标签: php authentication if-statement laravel passwords


    【解决方案1】:

    实际上,您应该检查源代码,它触手可及,所以当您使用以下代码时,为什么不深入挖掘:

    $user = User::find('1');
    $user->getAuthPassword();
    

    此代码返回当前实例化用户的密码,因此它是id=1 的用户,它可以是您可能想要的任何用户,取决于您,从数据库中检索谁。 getAuthPassword函数里面的代码是:

    public function getAuthPassword()
    {
        return $this->password;
    }
    

    因此,您从数据库中检索到的用户是否已登录并不重要。如果您使用id=10 检索用户,那么您也可以获得该用户的密码。

    另一方面,如下代码:

    Auth::user()->password;
    

    它返回当前登录用户的密码,因为Auth::user()返回当前登录用户实例,并且该方法仅在当前用户登录时有效。所以,是的,两种情况都有区别。

    【讨论】:

    • 感谢您的详尽解释,我确实理解它,但是嗯......真的不知道如何更清楚地表达我的好奇心。但是对于这两种情况,哪种方式会是更好的推荐方法?
    • @user1850712,实际上这取决于上下文。两者都可以,但如果您需要登录用户的密码,请使用Auth::user()
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2014-08-31
    • 2020-12-20
    • 2012-10-04
    • 2011-01-17
    • 2013-12-15
    • 2020-11-05
    • 2017-10-21
    相关资源
    最近更新 更多