laravel - 在 Laravel 中如何在特定字段旁边显示错误消息?
问题描述
我是 laravel 的新手。我创建了一个简单的页面,用户可以在其中将产品添加到数据库中。如果商品名称或金额为空;我也可以显示错误。但我想在特定字段旁边显示错误。如果标题为空,则错误将显示在标题字段旁边。我使用 JS 和其他方法搜索并找到了解决方案。但是有没有办法只使用 laravel 来实现这一点?
我的看法是这样的
<form method="POST" action="create">
@csrf
<input type="text" name="title" placeholder="Product name"><br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit"><br>
<button type="submit">Add Product</button>
</form>
@if(count($errors))
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
我的控制器是这样的
public function store()
{
$this->validate(request(),[
'title'=> 'required',
'amount' => 'required',
]);
$product = new Product;
$product->title = request('title');
$product->seller_id = Auth::guard('seller')->user()->id;
$product->description = request('description');
$product->amount = request('amount');
$product->save();
return redirect('/dashboard');
}
解决方案
您需要检查错误并显示在您想要的任何位置,如下所示
@if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> @endif
和
@if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> @endif
在您的查看代码中,它可以放置为
<form method="POST" action="create">
@csrf
<input type="text" name="title" placeholder="Product name">
@if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> @endif <br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit">
@if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> @endif <br>
<button type="submit">Add Product</button>
</form>
此外,您还可以通过从控制器返回错误文本来打印自定义消息,如下所示
$customMessages = [
'title.required' => 'The title field is required to be filled',
'amount.required' => 'The amount field should be completely filled'
];
$this->validate(request,[
'title'=> 'required',
'amount' => 'required',
], $customMessages);
相反,如果您想显示某个字段的所有错误,您可以按如下方式打印它们
@if ($errors->has('title'))
<p style="color:red;">
@foreach ($errors->get('title') as $errormessage)
{{ $errormessage }}<br>
@endforeach
</p>
@endif
推荐阅读
- reactjs - 如何使用按钮重置/清除 React Context
- c# - 弹跳一段时间后所有的幅度和速度都为 0 并停止
- go - 将标准输出和标准输入复制到 ssh 隧道,不适用于 fmt.Print
- groovy - Gremlin 根据其元属性检索多个属性
- typescript - ESLint 在 Visual Studio 2017 或 2019 中不起作用
- javascript - 使用 JavaScript 从二维数组中搜索单词
- javascript - jQuery:如果包含空子跨度,则将类添加到父 div
- time-series - 将大量传感器数据发送到 QuestDB 中哪种方法更快或更好?
- sql - SQL Query - 查找唯一数据条目的数量
- swift - NSTextField、文本选择和鼠标事件