在 Laravel 中验证没有电子邮件的用户

Authenticate users without email in Laravel

我正在尝试在用户注册时将电子邮件设置为可选。这里是package。所以我在这个函数中删除了email' => 'required|email|unique:users',

public function signup(Request $request)
{
    $credentials = $request->all();
    $validator = Validator::make($credentials, [
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6|confirmed',
        'password_confirmation' => 'required|min:3'
    ]);
    if ($validator->fails()) {
        throw new ValidationHttpException($validator->errors()->all());
    }
    try {
        $user = $this->users->create($request->except('roles', 'permissions'));
        if (!$user->id) {
            return $this->response->error('could_not_create_user', 500);
        }

        $hasToReleaseToken = Config::get('boilerplate.signup_token_release');
        if ($hasToReleaseToken) {
            return $this->login($request);

        }

        return $this->response->created();
    } catch (\Exception $e) {
        return $this->response->error($e->getMessage(), 500);
    }

}

然后在 config-boilerplate.php 中我也删除了电子邮件:

'signup_fields_rules' => [
    'name' => 'required',  
    'email' => 'required|email|unique:users',///// this
    'password' => 'required|min:6'
],

但是当我注册时我得到这个错误:

"message": "Undefined index: email", "status_code": 500, "debug": { "line": 173, "file": "/Users/MyMac/Desktop/Project/laravel-5.3-boilerplate-api-jwt-vue2/vendor/dingo/api/src/Http/Response/Factory.php", "class": "Symfony\Component\HttpKernel\Exception\HttpException",

路线:

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController@signup');

是否需要禁用任何功能以允许用户使用或不使用电子邮件进行注册?

如果您想将电子邮件作为可选字段,只需使用 sometimes|email 参见 Docs。试试下面的代码:

public function signup(Request $request)
{
    $credentials = $request->all();
    $validator = Validator::make($credentials, [
        'name' => 'required',
        'email' => 'sometimes|email',
        'password' => 'required|min:6|confirmed',
        'password_confirmation' => 'required|min:3'
    ]);
    if ($validator->fails()) {
        throw new ValidationHttpException($validator->errors()->all());
    }
    try {
        $user = $this->users->create($request->except('roles', 'permissions'));
        if (!$user->id) {
            return $this->response->error('could_not_create_user', 500);
        }

        $hasToReleaseToken = Config::get('boilerplate.signup_token_release');
        if ($hasToReleaseToken) {
            return $this->login($request);

        }

        return $this->response->created();
    } catch (\Exception $e) {
        return $this->response->error($e->getMessage(), 500);
    }

}

配置-boilerplate.php

'signup_fields_rules' => [
    'name' => 'required',  
    'email' => 'sometimes|email',///// this
    'password' => 'required|min:6'
],