首页 > 解决方案 > 我的项目 laravel 当我单击表单提交时输入错误我的视图刷新多次,所以我看不到消息错误

问题描述

这个问题存在于 chrome 中,但不存在于 opera 中,这是我的视图代码,我尝试使用 validate 和 div 执行表单,并带有错误类型:

@if(count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
<form action="add" method="POST">
{{ csrf_field() }} <!--Securite-->
    Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
    Product Price <input type="text"  class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>
@endsection

标签: laravellaravel-5bootstrap-4

解决方案


试试这个。

这将是您控制器中的一个功能。

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required', 
        'price' => 'required'
       
    ]);

    if ($validator->fails()) {
        return redirect('your-view-name')
                    ->withErrors($validator)
                    ->withInput();
    }

}

使用 foreach 查看错误

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

你的表格

<form action="{{url('/route-name')}}" method="POST">
@csrf
    Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
    Product Price <input type="text"  class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>

推荐阅读