如何修复验证数据库中客户是否存在时始终返回‘客户已存在’的错误
Let's break down the two critical issues in your code and fix them step by step:
Issue 1: Incorrect Query Filter
Your current query uses where('id', $campaigns_id) which targets the Participant model's primary key, not the campaign association. Since you're checking if customers exist in a specific campaign, you should filter by the campaign_id foreign key (which you correctly use when saving new participants).
Issue 2: Wrong Existence Check
get() returns a Laravel Collection object, even when there are no matching records. Using !empty() on this object will always return true (because the Collection itself exists, even if it's empty). Instead, use the Collection's built-in isNotEmpty() method to check for actual records.
Corrected Code
public function add(Request $request) { $request_data = $request->all(); $customer_ids = $request_data['ids']; $campaigns_id = $request_data['campaigns_id']; $customer_id_array = explode(',', $customer_ids); // Fix: Check for existing participants in the correct campaign $existingParticipants = Participant::where('campaign_id', $campaigns_id) ->whereIn('customer_id', $customer_id_array) ->get(); // Fix: Use Collection method to check for existing records if ($existingParticipants->isNotEmpty()) { // Optional: Return specific customer IDs that already exist for clarity $existingCustomerIds = $existingParticipants->pluck('customer_id')->toArray(); return [ 'code' => 402, 'status' => 'error', 'data' => $existingCustomerIds, 'message' => 'Some customers are already part of this campaign' ]; } foreach ($customer_id_array as $value) { $participantObj = new Participant; $participantObj->customer_id = $value; // Consistent arrow syntax for model properties $participantObj->campaign_id = $campaigns_id; // $participantObj->pin_number = $this->randomNumber(3) . '' . $key; $participantObj->save(); // No need for extra $data variable } return [ 'code' => 200, 'status' => 'success', 'message' => 'Customers added successfully' // Optional success feedback ]; }
Additional Improvements
- Used consistent arrow syntax (
->) for model property assignments (more readable than array access for models). - Removed unnecessary variable assignments (e.g.,
$data = $participantObj). - Added optional feedback to return exactly which customers already exist, making debugging easier for your users.
内容的提问来源于stack exchange,提问作者Mahajan nidhi

