dsag14654 2015-10-09 09:52
浏览 26
已采纳

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

I am fairly new to laravel and I am trying to create a login functionality in laravel 4.2 where the username and password is fetched from the database. I am planning to use this code in the controller but i don't know how to tweak it in such a way that the username and password should be based from a database record

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

Any ideas? Thanks for any help in advance.

  • 写回答

1条回答 默认 最新

  • dswwuo1223 2015-10-09 10:40
    关注

    You don't need to tweak that code. Default behavior of Auth is to use the eloquent driver which uses the database you configured with your app.

    So Auth::attempt($credentials) will use the database table associated (default users table) to authenticate the user with the provided credentials.

    You can change the model or table name like opitons in Auth.php file in config directory.

    Edit

    To validate and login a user manually use the following.

    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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?