当我验证产品名称并发送消息product name is exist before
以查看时,我具有多个数据库连接。
消息出现在视图中,但所有表单输入均被清除。 考虑产品名称不存在时如何解决此问题。验证正确执行,如果发现验证错误,则该错误会正常出现,并且表单输入未清除。 这是我的控制器代码。
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
这是我的观点
@extends('layout.header')
@section('content')
@if(isset($message))
{{$message}}
@endif
@if(count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
@endsection
这是我的路线
Route::get('/products/add',"produtController@add");
Route::post('/products/add',"produtController@add");
答案 0 :(得分:0)
您可以手动引发验证异常的第一种方法。 Here,您可以找到解决方法。
第二种方式(我推荐这种方式),您可以生成一个custom validation rule。顺便说一下,您的控制器方法将更干净。
答案 1 :(得分:0)
您可以创建自己的自定义验证功能,如下所示。我想这应该对您有帮助。
从https://laravel.com/docs/5.8/validation#custom-validation-rules->使用闭包中找到它
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);