【问题标题】:How to validate if user already exists?如何验证用户是否已经存在?
【发布时间】:2021-10-29 02:48:39
【问题描述】:

我想验证它是否已经存在于数据库中,然后显示一条错误消息。但在这两种情况下,我总是得到user already exists。我该如何解决?

下面是我的代码:

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);
    $whereIn = $customer_id_array;
    $check_customer = Participant::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get();

    if (!empty($check_customer)) {
        return ['code' => 402, 'status' => 'error', 'data' => $check_customer, 'message' => 'Customer Already Exists'];
    }

    foreach ($customer_id_array as $key => $value) {
        $participantObj = new Participant;

        $participantObj['customer_id'] = $value;
        $participantObj->campaign_id = $campaigns_id;
        // $participantObj->pin_number =  $this->randomNumber(3).''.$key;

        $data = $participantObj;
        $data ->save();
    }

    return['code' => 200, 'status' => 'success'];
}

【问题讨论】:

  • 你总是会得到402,因为->get();总是会返回一个Collection,所以当你做!empty($check_customer)时就是true。阅读documentation,因为它在那里解释......
  • 这能回答你的问题吗? Laravel unique validation
  • 但我必须同时满足这两个条件。 $check_customer = 参与者::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get(); .我想我需要这张 unqiue 支票

标签: php laravel validation


【解决方案1】:

改变这一行

if (!empty($check_customer)) {

if ($check_customer->isNotEmpty()) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2020-06-21
    相关资源
    最近更新 更多