登录验证失败

时间:2018-02-20 08:17:31

标签: php laravel laravel-5

我正在尝试验证登录系统的用户。我使用散列密码来存储密码。当我尝试验证用户时,我收到如下错误:

strlen() expects parameter 1 to be string, array given

我已经搜索了解决这个问题的各种方法,但我找不到办法。

这是我的代码。

Controller.php这样

public function logs_in(Request $request){
    $email = $request->input('email');
    $password = $request->input('password');


    $hashedPassword = DB::select('select password from users where email = ?', [$email]);


    if(Hash::check($password, $hashedPassword)){
        $request->session()->put('success');
        return redirect()->route('admin');
    } else {
        return redirect()->route('login')->with('login_error', 'Invalid 
        credentials entered');
    }
}

可能出现什么问题?

3 个答案:

答案 0 :(得分:3)

您必须将first()collect()一起使用,因为您的查询返回数组

    $hashedPassword = collect(DB::select('select password from users where email = ?', [$email]))->first();

其次,你必须

if(Hash::check($password, $hashedPassword->password)){
    $request->session()->put('success');
    return redirect()->route('admin');
}

DB::table('users')->where('email', $email)->first();

希望这有帮助

答案 1 :(得分:2)

public function logs_in(Request $request)
{
    $hashedPassword = User::where('email', $request->get('email'))->first();


    if (Hash::check($request->get('password') == $hashedPassword->password))
    {
        // Yay it worked!
    } else {
        // You Borked it... Try again...
    }
}

您不必在查询中运行select password,因为默认情况下它会全部选择。但是,您必须始终在查询结尾处运行->get()->first()。 - > get()表示您可以使用数组,因此$hashedPassword['password']first()之类的内容为$hashedPassword->password

答案 2 :(得分:0)

public function logs_in(Request $request){
    $email = $request->input('email');
    $password = $request->input('password');


    $hashedPassword = collect(DB::select('select password from users where email = ?', [$email]))->first();


    if(Hash::check($password, $hashedPassword)){
      if (Hash::check($request->get('password') == $hashedPassword->password)){
        $request->session()->put('success');
        return redirect()->route('admin');
      } else {
        return redirect()->route('login')->with('login_error', 'Invalid 
        credentials entered');
      }

    } else {
        return redirect()->route('login')->with('login_error', 'Invalid 
        credentials entered');
    }
}

此处电子邮件应该是唯一的,因此一个用户只能收到一封电子邮件。所以在这里使用 - > first()。