在Laravel中如何在特定字段旁边显示错误消息? [英] In Laravel how to show error message beside specific field?
问题描述
我是laravel的新手.我创建了一个简单的页面,用户可以在其中将产品添加到数据库中.如果产品标题或金额为空;我也可以显示错误.但是我想在特定字段旁边显示错误.如果标题为空,则错误将显示在标题字段旁边. 我搜索并找到了使用JS和其他方法的解决方案.但是有没有办法仅使用laravel来实现呢?
I am new to laravel. I created a simple page where a user can add a product to the database. If the product title or amount is empty; I can also show the errors. But I want to show error right beside the specific field. If the title is empty the error will show beside the title field. I searched and found solutions using JS and some other. But is there a way to achieve this using only 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');
}
推荐答案
您需要检查错误并在需要的地方显示,如下所示
You need to check for errors and display wherever you want like given below
@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
在您要查看的代码中,可以将其放置为
In your code for view it can be placed as
<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>
此外,您还可以通过如下所示从控制器返回错误文本来打印自定义消息
Additionally you can also print custom messages by returning the error text from controller as shown below
$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);
相反,如果要显示某个字段的所有错误,可以按如下所示打印它们
Instead, if you want to show all the errors for a field you can print them as follows
@if ($errors->has('title'))
<p style="color:red;">
@foreach ($errors->get('title') as $errormessage)
{{ $errormessage }}<br>
@endforeach
</p>
@endif
这篇关于在Laravel中如何在特定字段旁边显示错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!