In my system what i want to include is that user can put three addresses.And that three addresses should be unique to that user only not other user.
I have used ajax validation for the system.But i couldnot figure out logic.
Everytime i try i got email address has already taken even to different user.
所以任何人都可以帮助我如何为特定用户制作唯一的地址。
我所做的只是简单的ajax发布和验证。所有代码都是正确的,我只希望逻辑在address_name字段中为特定的userCustomer进行唯一验证。谢谢。
这是我的代码:
public function AddNewAddress(Request $request)
{
if(!request()->ajax()){
return false;
}
$customerId = Auth::user()->userCustomer;
$user = Auth::user()
$customer = $user->userCustomer()->firstOrFail()
$userAddresses = $customer->customerAddresses()->latest()->get();
$validator = Validator::make($request->all(), [
'house_building'=>'required',
'country_name'=>'required',
'city_name'=>'required',
'district_name'=>'required',
'address_name'=>'required|unique:user_customer_addresses,address_name,'.$userAddresses->get('customer_id'),
'street'=>'required',
'house_floor_number'=>'required',
'extra_direction'=>'required'
]);
if ($validator->fails()) {
return response()->json(array(
'status' => 'fails',
'errors' => $validator->getMessageBag()->toArray()
));
}
if ($validator->passes()) {
//
$count = count($userAddresses);
if ($count >= 3) {
session()->flash('Address_message', 'Limit upto 3.Please delete one of your address for updating new address');
return response()->json(array(
'status' => 'success',
'url' => url('user/AddressUpdate')
));
} else {
UserCustomerAddress::create([
'customer_id' => $customerId->id,
'city_name' => $request->city_name,
'district_name' => $request->district_name,
'house_building' => $request->house_building,
'address_name' => $request->address_name,
'street' => $request->street,
'house_building' => $request->house_building,
'house_floor_number' => $request->house_floor_number,
'extra_direction' => $request->extra_direction,
'floor' => $request->floor,
'building' => $request->building
]);
session()->flash('Address_message', 'Your AddressInformation has been created');
return response()->json(array(
'status' => 'success',
'url' => url('user/AddressUpdate')
));
}
}
}
提前致谢。
答案 0 :(得分:0)
似乎唯一的验证规则使用' id'除了功能的列。 尝试通过' customer_id'作为第四个参数
'address_name'=>'required|unique:user_customer_addresses,address_name,'.$userAddresses->get('customer_id').',customer_id'
修改强>
unique:table,column,except,idColumn
table - your table name,
column - column name under validation,
except - id's of items which you want to exclude from valiadation,
idColumn - id'columns name
例如:
我有user_addresses表和字段(id,name,user_id),我需要检查所有地址属于一个用户是唯一的。
我案例的验证规则是:
'address'=>'unique:user_addresses,name,'.$user->id.',user_id'