Search code examples
laravellaravel-authentication

Laravel auth optional field?


In laravel auth

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'],
    ]);
}   

requires that

$data ['affiliate']

is defined... what if i want it optional can i send a null instead? the database is nullable maybe somthing like

if $data ['affiliate'] is defined create, but if not leave null or create 0


Solution

  • Use the data_get helper:

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

    @AnkitPatel suggested array_get which works too. data_get works on both arrays and objects.