laravel 4.2基于数据库记录的登录功能


Login functionality in laravel 4.2 based on database records

我对laravel相当陌生,我试图在laravel 4.2中创建一个登录功能,其中用户名和密码是从数据库中获取的。我计划在控制器中使用此代码,但我不知道如何调整它,以使用户名和密码应该基于数据库记录

public function postLogin()
{
    $credentials = [
        'username'=>Input::get('username'),
        'password'=>Input::get('password')
    ];
    $rules = [
        'username' => 'required',
        'password'=>'required'
    ];
    //validating the credentials.
    $validator = Validator::make($credentials,$rules);
    //in case the credentials are valid. Try to login the user.
    if($validator->passes())
    {
        if(Auth::attempt($credentials))
        {
            //if successfull redirect the user 
            return Redirect::to('user/home');
        }
        //else send back the login failure message.
        return Redirect::back()->withInput()->with('failure','username or password is invalid!');
    }
        //send back the validation errors.
    return Redirect::back()->withErrors($validator)->withInput();
}

public function getLogout()
{
    Auth::logout();
    return Redirect::to('/');
}

任何想法?谢谢你的帮助。

您不需要调整该代码。Auth的默认行为是使用eloquent驱动程序,该驱动程序使用您在应用程序中配置的数据库。

因此Auth::attempt($credentials)将使用相关联的数据库表(默认的users表)使用提供的凭据对用户进行身份验证。

您可以像config目录下的Auth.php文件中的选项一样更改模型或表名。

编辑

要手动验证和登录用户,请使用以下命令。

public function postLogin()
{
    $credentials = Input::only('username', 'password');
    $validator = Validator::make($credentials, [
        'username' => 'required',
        'password'=>'required'
    ]);
    if($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    $user = User::where('SystemUserName', $credentials['username'])->first();
    if (! $user || ! Hash::check($credentials['password'], $user->SystemUserPassword)) {
        return Redirect::back()->withInput()->with('failure','username or password is invalid!');
    }
    Auth::login($user);
    return Redirect::to('user/home');
}