0

在 laravel 身份验证中

注册控制器.php

protected function create(array $data) 
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'affiliatetoken' =>Str::random(12),
        'affiliate' => $data ['affiliate'],
    ]);
}   

要求

$data ['附属']

已定义...如果我希望它是可选的,我可以发送一个空值吗?数据库可以为空,可能类似于

如果$data ['affiliate']定义了创建,但如果没有离开null或创建0

4

2 回答 2

1

使用data_get助手:

// 3rd argument is what to default to if the key is not set. null by default
'affiliate' => data_get($data, 'affiliate'), 

@AnkitPatel 建议array_get也可以。data_get适用于数组和对象。

于 2018-07-05T01:57:45.940 回答
0

用这个

protected function create(array $data) 
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'affiliatetoken' =>Str::random(12),
        'affiliate' => $data ['affiliate'] ?? null, // or 0 "?? operator is equivalent isset()"
    ]);
}  
于 2018-07-05T08:39:17.430 回答