实施“;记住我";使用Laravel 4


Implementing "Remember Me" functionality using Laravel 4

我是Laravel的新手,正在尝试制作一个非常简单的登录表单。

此表单有一个"记住我"复选框。我试图使用Cookie::make()实现它的功能,但结果发现我需要返回一个Response才能保存它

当我在浏览器中检查从localhost存储的cookie时,我找不到名为username的cookie。我做了一些研究,结果发现我必须将cookie附加到Response中,然后将其返回。

问题是,我不想返回Response!!

在我的学习过程中,我还没有达到Auth级。因此,不使用此类的解决方案会更合适。

这是我的代码:

public function processForm(){
    $data = Input::all();
    if($data['username'] == "rafael" & $data['password'] == "123456"){
        if(Input::has('rememberme')){
            $cookie = Cookie::make('username', $data['username'], 20);
        }
        Session::put('username', $data['username']);
        return Redirect::to('result');
    } else {
        $message_arr = array('message' => 'Invalid username or password!');
        return View::make('signup', $message_arr);
    }
}

我的signup.blade.php:

@extends('layout')
@section('content')
    @if(isset($message))
        <p>Invalid username or password.</p>
    @endif
    <form action="{{ URL::current() }}" method="post">
        <input type="text" name="username"/>
        <br>
        <input type="text" name="password"/>
        <br>
        <input type="checkbox" name="rememberme" value="true"/>
        <input type="submit" name="submit" value="Submit" />
    </form>
@stop

routes.php:

Route::get('signup', 'ActionController@showForm');
Route::post('signup', 'ActionController@processForm');
Route::get('result', 'ActionController@showResult');

您应该查看Laravel 4关于验证用户的文档,该文档位于:

http://laravel.com/docs/security#authenticating-用户

基本上,您可以通过将$data传递给Auth::attempt()来对用户进行身份验证。将true作为第二个参数传递给Auth::attempt(),以记住用户以备将来登录:

$data = Input::all();
if (Auth::attempt($data, ($data['rememberme'] == 'on') ? true : false)
    return Redirect::to('result');
else
{
    $message_arr = array('message' => 'Invalid username or password!');
    return View::make('signup', $message_arr);
}

您应该使用Laravel的方法进行身份验证,因为它可以处理密码提醒等问题。