以下是检查记录是否重复的代码。
$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
答案 0 :(得分:2)
确保数据库表包含Unique Constraint。
$v = Validator::make($request->all(), [
'Category' => 'required|unique:tblcategory|max:100|min:5'
]);
$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.']);