Laravel Auth可选字段?

时间:2018-07-05 01:19:16

标签: laravel laravel-authentication

在laravel身份验证

registercontroller.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 ['affiliate']

已定义...如果我希望它是可选的,我可以改为发送空值吗?数据库是可空的,也许像

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

2 个答案:

答案 0 :(得分: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对数组和对象均有效。

答案 1 :(得分: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()"
    ]);
}