Laravel响应代码和消息

我正在使用Laravel 5.3和https://github.com/1000hz/bootstrap-validator

我正在检查Laravel中我的数据库的用户电子邮件,以检查电子邮件是否正在使用中 .

Bootstrap Validator上的文档声明如果电子邮件地址正常(即不存在)则返回200,如果存在则返回4xx错误 .

在我的Laravel功能中,我正在执行以下操作:

public function check_email(Request $request)
{
    // Email Address
    $email = User::where('email', $request->input('email'))
            ->take(1)
            ->get();

    $email = $email->toArray();

    if(empty($email))
    {
        return response()->json(['Email Not Taken'], 200);
    }
    else
    {
        return response()->json(['Email In Use'], 400);
    }
}

现在当我运行验证器时,它没有显示消息 . 这是因为Laravel对其响应代码更加严格吗?或者我只是做错了什么?

我的HTML代码如下:

<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                                    <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email" data-remote="/validate-email" data-error="Please enter your Email Address" required="required">
                                    @if ($errors->has('email'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('email') }}</strong>
                                         </span><!-- /.help-block -->
                                    @endif
                                    <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                                    <div class="help-block with-errors"></div>
                            </div><!-- /.form-group -->

如何在Larvel 5.3中使用消息设置4xx响应?

谢谢

回答(2)

3 years ago

首先,不要't check if the user exists via a query use Laravel'的验证员类https://laravel.com/docs/5.3/validation它已经为你完成了这项工作,请参阅:https://laravel.com/docs/5.3/validation#rule-unique

其次,看看这个库已经做了你需要的东西:https://github.com/proengsoft/laravel-jsvalidation

3 years ago

您必须在控制器中进行验证或创建请求类

https://laravel.com/docs/5.3/validation

public function check_email(Request $request)
{
    //validate 
    $this->validate($request, [
        'email' => 'required|unique:users',
    ]);

    // Email Address
    $email = User::where('email', $request->input('email'))
            ->take(1)
            ->get();
}