首页 > 解决方案 > 在 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');
}

标签: laravellaravel-5

解决方案


您需要检查错误并显示在您想要的任何位置,如下所示

@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

推荐阅读