Laravel / Lumen:验证已存在的电子邮件数据和一般验证

时间:2015-08-23 16:15:48

标签: validation laravel lumen

我正在编写API。我想知道我怎么能回复正确的答案。

  • 数据无效(仅当电子邮件存在时)
  • 数据无效(一般验证错误)

到目前为止,这是我的代码:

$data = Input::all();

$validator = Validator::make($request->all(), [
    'email'            => 'required|email|unique:users,email',
    'some_other_field' => 'required'
]);

if ($validator->fails()) {
    // NOTE: using a or b, this are my custom methods
    a) return $this->existsResponse($data);
    b) return $this->badRequestResponse($data);
}

我怎么能弄清楚电子邮件是否已经存在?

3 个答案:

答案 0 :(得分:0)

您应该查看Validator类。我认为Methods invalid()和valid()应该适合你。这个方法为您提供了一系列密钥。

http://laravel.com/api/5.0/Illuminate/Validation/Validator.html#method_invalid

答案 1 :(得分:0)

嗯,您正在尝试进行两种不同类型的验证,因此使用两种不同的验证器是有意义的:

$data = $request->all();

// validate email
$validator = Validator::make($data, [
    'email' => 'required|email|unique:users,email',
]);

if ($validator->fails()) {
    return $this->existsResponse($data);
}

// email valid, so validate other data
$validator = Validator::make($data, [
    'some_other_field' => 'required'
]);

if ($validator->fails()) {
    return $this->badRequestResponse($data);
}

// if here, all data is valid

答案 2 :(得分:0)

我已经解决了这个问题。

public function store(Request $request)
{
    $data = Input::all();

    // validating data

    $validator = Validator::make($request->all(), [
        'email'            => 'required|email',
        'some_other_field' => 'required'
    ]); 

    if ($validator->fails()) {
        return $this->badRequestResponse($data);
    }

    // validating if resource exists

    $userExists = User::where('email', $request->email)->count();

    if($userExists) {
        return $this->existsResponse($data);
    }

    // inserting data

    $user = new User();

    $user->fill($data);
    $user->save();

    if($user->save()) {
        return $this->createdResponse($data);
    }
}