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

时间:2015-12-14 05:55:12

标签: php laravel-5 laravel-5.1

以下是检查记录是否重复的代码。

$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

3 个答案:

答案 0 :(得分:2)

解决方案: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();

}

答案 1 :(得分:0)

试试吧

创建 CategoryFormRequest

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Support\Facades\Input;

class CategoryFormRequest extends Request {

    public function authorize() {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        $rules = [
            'Category' => ' required|unique:categories,Category',
        ];
        if ($this->method() == 'PUT') {
            $rules['Category'] = 'required|unique:categories,Category,' . $this->category;
        }
        return $rules;
    }

}

您的控制器代码

use App\Http\Requests\CategoryFormRequest as CategoryFormRequest;
......
......
 public function store(CategoryFormRequest  $request) {
  .......
  ....... 
}

参考: - laravel中的Request课程

答案 2 :(得分:0)

您可以返回包含以下错误的视图:

return view('my_view')->withErrors(['Duplicate Record.']);