试试这个。
这将是您控制器中的一个功能。
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>
@if (count($errors))
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
@endif