【问题标题】:Username/password Authentication Rules in LaravelLaravel 中的用户名/密码认证规则
【发布时间】:2013-05-27 07:21:30
【问题描述】:

目前,当用户登录我的 Laravel 应用时,我使用以下规则...

// Validation rules
$rules = array(
    'email' => 'required|email|exists:users,email',
    'password' => 'required'
);

我正在寻找的是用于检查用户密码的验证规则。

【问题讨论】:

    标签: php validation laravel laravel-4


    【解决方案1】:

    来自docs:

    if (Auth::attempt(array('email' => $email, 'password' => $password))) {
        return Redirect::intended('dashboard');
    }
    

    例子:

    $userdata = array(
        'email'    => Input::get('email'),
        'password' => Input::get('password')
    );
    
    $rules = array(
        'email' => 'required|email|exists:users,email',
        'password' => 'required'
    );
    
    // Validate the inputs.
    $validator = Validator::make($userdata, $rules);
    
    // Check if the form validates with success.
    if ($validator->passes()) {
        // Try to log the user in.
        if (Auth::attempt($userdata)) {
            // Redirect to homepage
            return Redirect::to('')->with('success', 'You have logged in successfully');
        } else {
            // Redirect to the login page.
            return Redirect::to('login')->withErrors(array('password' => 'Password invalid'))->withInput(Input::except('password'));
        }
    }
    

    【讨论】:

    • Ahhhh .. 有道理.. 谢谢你
    • @Valery Viktorovsky 你的例子让我很困惑。您应该验证的email 字段在哪里?为什么将username 字段输入两次用作id?为什么你需要unsetusername,因为你一开始甚至没有验证它,所以你甚至不需要它?为什么在 withErrors 方法中传递与验证器对象不同的东西?
    • 谢谢,我修正了错字。 $userdata 必须是 $userdata = array('email' => Input::get('email'), 'username' => Input::get('username'), 'password' => Input::get('密码')); 'Auth::attempt' 需要包含 2 个元素的数组:列名对应于“用户名”和密码。
    • @ValeryViktorovsky 好的,现在它更有意义了,但是您仍然不需要 username 输入,因为您不使用它,我认为将数组作为参数传递给withErrors 方法。
    • @yannishristofakis 这只是示例,所以我不包括自定义用户名验证。如果它让您感到困惑,我删除了与用户名相关的代码。我认为您应该查看 laravel 代码(withErrors 方法)github.com/laravel/framework/blob/master/src/Illuminate/Http/…。 withErrors 方法使用 MessageBag,它需要数组作为参数 (github.com/laravel/framework/blob/master/src/Illuminate/Support/…)
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2011-11-19
    相关资源
    最近更新 更多