In validation I didn't set the product field name to unique but want to it unique in some ways like products with same user_id, I want a single user have unique products name. So did some code to match value which is product field name to an array of product names from database.
$products = Product::find(auth()->user()->id)->get();
foreach ($products as $product) {
$pro_name = $product->name;
}
$value = Input::get('name');
if ($value == anyOf($pro_name) {
return false;
}
i assume user_id is not the primary key to your product table. so you can't use find. do it like:
$products = Product::where(user_id, auth()->user()->id)->get();
you need an array of products name. get it like this:
$pro_name = Product::where(user_id, auth()->user()->id)->pluck('name')->toArray();
to check the array for a certain key use:
if (in_array($value, $pro_name)) {
return false;
}
also you can do the whole thing like this:
$value = Input::get('name');
$product = Product::where(user_id, auth()->user()->id)->where('name', $value)->first();
if ($product){
return false;
}
It is also possible to define this validation using standard Laravel validation:
$this->validate(
$request,
[
'name' => \Illuminate\Validation\Rule::unique('products', 'name')
->ignore($id) // id of product being updated. If it is a new product you can remove this, or pass null
->where(function ($query) {
return $query->where('user_id', \Auth::user()->id);
})
]
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.