使用Laravel 4实现“记住我”功能

时间:2013-08-31 18:57:09

标签: php cookies laravel laravel-4 remember-me

我是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');

1 个答案:

答案 0 :(得分:5)

您应该查看Laravel 4关于用户身份验证的文档,可以在以下网址找到:

http://laravel.com/docs/security#authenticating-users

基本上,您可以通过将$ 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的方法进行身份验证,因为它会处理密码提醒等。

相关问题