如果表单验证失败,则不会显示Laravel 5.5验证错误

时间:2018-11-20 07:56:31

标签: laravel laravel-5.5

我正在尝试显示表单错误,以防表单验证失败。一切正常,并且表单已正确验证,但视图中未显示表单错误。每次返回一个空数组作为错误。

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    public function storeProjectDetails(Request $request)
   {
    $messages = [
        'title.required' => 'Please enter trip title',
        'title.max' => 'Only 254 characters are allowed as trip title',
        'startDate.required' => 'Please enter trip start date',
        'startDate.date' => 'Only date formats are allowed as start date',
        'endDate.required' => 'Please enter trip end date',
        'endDate.date' => 'Only date formats are allowed as end date',
    ];

    $this->validate($request,[
        'title' => 'required|string|max:254',
        'startDate' => 'required|date',
        'endDate' => 'required|date',
    ]);

  }
}

查看:

  print_r($errors->all());

3 个答案:

答案 0 :(得分:0)

使用了

@if($errors->has())
   @foreach ($errors->all() as $error)
      <div>{{ $error }}</div>
  @endforeach
@endif

答案 1 :(得分:0)

首先,您需要使用if条件检查错误,然后使用如下所示的循环打印错误

@if ($errors->any())
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
@endif

在您的情况下,您不希望在控制器中返回错误数组。请尝试下面给出的验证检查。

$this->validate($request,[
        'title' => 'required|string|max:254',
        'startDate' => 'required|date',
        'endDate' => 'required|date',
    ], $messages);

答案 2 :(得分:0)

您正在以错误的格式构建message数组,它看起来应该像这样:

$messages = [
    'required' => 'Please enter :attribute',
    'date' => 'Only date formats are allowed as :attribute',
    ...
];