0

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

Brian Lee
  • 17,904
  • 3
  • 41
  • 52
Tera
  • 121
  • 3
  • 12
  • Use `isset($data['affiliate']) ? $data['affiliate'] : null` – Justinus Hermawan Jul 05 '18 at 01:22
  • Yes, You can send a null value. If the content in the ```$data['affiliate']``` is ```empty``` or ```null```, if you are using Laravel 5.6 it will automatically return a null. However, your database must have a nullable column in order to do that. – Sithira Jul 05 '18 at 01:25
  • 1
    you can use Laravel array helper for this, just use array_get($data,'affiliate','default Value'); if you don't set the third argument it will set as default – ankit patel Jul 05 '18 at 01:26
  • Just for your info nothing fancy: if you are using any kind of validations before creating a record, then you can use nullable validation rule. – dipenparmar12 Jan 28 '20 at 10:12

2 Answers2

1

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.

Brian Lee
  • 17,904
  • 3
  • 41
  • 52
0

use this

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()"
    ]);
}  
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55