这意味着未定义的索引:Laravel 中的 team_id

which means Undefined index: team_id in Laravel

我正在更改注册流程。当用户被邀请时,用户被分配到同一个团队。并且如果他自己注册,他可以选择一个团队。

一切正常,除了 team_id。我总是收到错误消息:

Undefined index: team_id

错误信息是什么意思?我该如何修复错误?

我不明白为什么这不起作用,因为相同的功能与头像一起使用。

函数:

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:30',
        'username' => 'required|string|max:20|alpha_num|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'birthday' => 'required|date|before_or_equal:-16 years',
        'agb' => 'accepted',
        'gender' => 'required|boolean',
        'team_id' => 'numeric'
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    if($data['gender'])

    {
        $avatar = 'defaults\avatars\male.jpg';
    }

    else

    {
        $avatar = 'defaults\avatars\female.jpg';
    }



if($data['team_id'])
        {
            $team = $data['team_id'];
        }

        else
        {
            $team = Null;
        }


    $user = User::create([
        'name' => $data['name'],
        'team_id' => $team,
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'birthday' => $data['birthday'],
        'gender' => $data['gender'],
        'slug' => str_slug($data['username']),
        'avatar' => $avatar,
        'active' => false,
        'activation_token' => str_random(255)
    ]);

    Profile::create(['user_id' => $user->id ]);

    while (true) {
        $randomstring = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 7);
        if (Invite::where('url','!=', $randomstring)->exists()) {
            Invite::create([
            'user_id' => $user->id,
            'url' => $randomstring
            ]);
            break;
        }
    }
    return $user;
}

阅读错误,您将能够理解其含义。

看到这一行:

if($data['team_id'])

如果 $data 数组不包含 team_id 索引怎么办?此代码无效。如果要验证,必须使用use array_key_exists()

if (array_key_exists('team_id', $key) && $data['team_id'])

if (isset($key['team_id']) && $data['team_id'])

这两种方法都是安全的方法来做你想做的事。