Laravel:为什么没有显示验证消息?

时间:2018-01-22 06:36:15

标签: laravel

我在托管上使用Laravel 5.4。我的验证方法正常,但它不显示消息。我做了显示错误所需的所有操作,但它不起作用。

@if($errors->has('recipient'))
<div class="form-group">
<label class="col-lg-2 control-label"></label>  
<div class="col-lg-10">                     
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->get('recipient') as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
</div>
</div>
@endif

我使用{{ csrf_field() }}令牌。如果使用了错误的用户类型,则验证规则有效,但不显示消息。

我的send方法:

public function send(Request $request)
{
   $this->validator($request->all())->validate();
   $this->create($request->all());
   return redirect($this->redirectToAfterSendMessage);
}

我的验证码:

protected function validator(array $data)
{        
    return Validator::make($data, [

        "$this->recipient" => [
            'sometimes',
            'required',
            'email',
            'exists:users,email',
            Rule::notIn([auth()->user()->email])
        ],

        "$this->subject" => 'sometimes|required|min:10',

        "$this->message" => 'sometimes|required|min:50',

    ], $this->validator_messages());
}

我的路线:

Route::get('/compose', 'InboxController@compose')     ->name('compose');
Route::post('/compose', 'InboxController@send');

dump($errors)的结果:

ViewErrorBag {#244 ▼
  #bags: []
}

2 个答案:

答案 0 :(得分:1)

您需要更改:

"$this->recipient"
"$this->subject" 
"$this->message"

要:

'recipient'
'subject'
'message'

答案 1 :(得分:1)

<强> EDITED

要解决当前问题,请将$errors->get('recipient')更改为$errors->all()

它应该是这样的:

@foreach ($errors->all() as $error)
   <li>{{ $error }}</li>
@endforeach

-

这不是您问题的直接解决方案。然而,比你更好的方法(imo)是自定义请求。您可以使用以下命令快速生成自定义请求:

php artisan make:request CustomRequest

之后,您可以将类型从Request更改为CustomRequest

public function send(CustomRequest $request)
{
   $this->create($request->all());
   return redirect($this->redirectToAfterSendMessage);
}

在CustomRequest.php中,您可以像这样提取验证逻辑:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CustomRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required',
            'message' => 'required',

        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Name is required.',
            'email.required' => 'Email is required.',
            'message.required' => 'Message is required.',
        ];
    }
}

希望这有帮助。