php – 在视图中显示错误列表中的重复错误消息:Laravel 5

下面是我检查记录是否重复的代码.

$Category = \App\Models\Category_Model
           ::where("Category", "=", $request->input('Category'))->first();
if($Category != null) {
    return 'Duplicate';
}

有没有办法在验证规则中注入此错误消息,以便在查看以下部分中的错误列表中显示此错误消息?

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

最佳答案 解决方案:1

Reference : unique:Name of the Table:

确保数据库表包含Unique Constraint.

$v = Validator::make($request->all(), [
    'Category' => 'required|unique:tblcategory|max:100|min:5'
]);

解决方案:2

$Category = \App\Models\Category_Model
            ::where("Category", "=", $request->input('Category'))->first();

if($Category != null) {

    $v->errors()->add('Duplicate', 'Duplicate Category found!');

    return redirect('Create-Category')
                ->withErrors($v)
                ->withInput();

}
点赞