【问题标题】:Laravel 4 error passing not workingLaravel 4错误传递不起作用
【发布时间】:2013-11-07 17:34:47
【问题描述】:

我正在尝试创建一个身份验证系统,我遇到的唯一问题是,如果使用了错误的凭据,它不会显示错误。它在其中一个字段为空时显示错误,但在它们都填充了错误信息时不显示。有人可以帮我找出问题所在吗?感谢大家的帮助!

这是我的看法

{{ Form::open([
        "route"=>"user/login",
        "autocomplete"=>"off"
    ]) }}

        {{ Form::label("username", "Username") }}
        {{ Form::text("username", Input::old("username"), [
            "placeholder"=>"Username"
        ]) }}

        {{ Form::label("password", "Password") }}
        {{ Form::password("password", [
            "placeholder"=>"Password"
        ]) }}

        @if($error = $errors->first("password"))
            <div class="error">
                {{ $error }}
            </div>
        @endif

        {{ Form::submit("Login") }}

    {{ Form::close() }}

这里是控制器

<?php

use Illuminate\Support\MessageBag;

class UserController extends BaseController
{
    public function loginAction()
    {
        $errors = new MessageBag();

        if($old = Input::old("errors")) {
            $errors = $old;
        }

        $data = [
            "errors"=>$errors
        ];

        if(Input::server("REQUEST_METHOD") == "POST") {
            $validator = Validator::make(Input::all(), [
                "username"=>"required",
                "password"=>"required"
            ]);

            if($validator->passes()) {
                $credentials = [
                    "username"=>Input::get("username"),
                    "password"=>Input::get("password")
                ];

                if(Auth::attempt($credentials)) {
                    //return Redirect::route("user/login");
                    echo "login success";
                }
            } else {
                echo "Login failed";
                $data["errors"] = new MessageBag([
                    "password"=>[
                        "Username and/or password invalid."
                    ]
                ]);
                $data["username"] = Input::get("username");

                return Redirect::route("user/login")
                    ->withInput($data);
            }
        }

        return View::make("user/login", $data);
    }
}

【问题讨论】:

    标签: php validation laravel laravel-4 blade


    【解决方案1】:

    如果身份验证失败,您似乎没有显示任何消息。 Auth::attempt() 将尝试匹配用户名和密码,如果失败,它应该在错误数组中添加一些内容。

    if(Auth::attempt($credentials)) {
          //return Redirect::route("user/login");
          echo "login success";
        }
    else  // add this
    {
       echo 'login failed - username and/or password provided are not correct';
    }
    

    也就是说,您可能需要在此处添加 else 声明。

    【讨论】:

    • 就是这样!这样做之后,我还必须在 validator passes 条件的末尾添加另一个 else 以说明空字段。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2015-02-20
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多