In a model, how are we able to insert a nullable validated field with the create function? For example, in the RegisterController: the basic validator + the create function. If I didn't send the google_id
or facebook_id,
the create function returns an undefined index (obviously) on the fields. What's the proper way to insert them?
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['nullable', 'email', 'unique:users'],
'google_id' => ['nullable', 'string', 'unique:users'],
'facebook_id' => ['nullable', 'string', 'unique:users'],
'twitter_id' => ['nullable', 'string', 'unique:users'],
'phone' => ['required', 'string', 'max:10', 'min:10', 'unique:users', "regex:/(^[1-9][0-9]*$)/"],
'country_code' => ['required', 'string', 'max:255', 'exists:'.config('countries.table_name').',calling_code'],
'password' => ['required', 'string', 'min:8'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['country_code'].$data['phone'],
'google_id' => $data['google_id'] ? $data['google_id'] : null,
'facebook_id' => $data['facebook_id'] ? $data['facebook_id'] : null,
'twitter_id' => $data['twitter_id'] ? $data['twitter_id'] : null,
'password' => Hash::make($data['password']),
]);
}
I know it's a fundamental question, and I do know how to ignore them, but I need to know what the correct format is.
Use the new format available in php 7
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['country_code'].$data['phone'],
'google_id' => $data['google_id']??null,
'facebook_id' => $data['facebook_id']??null,
'twitter_id' => $data['twitter_id']??null,
'password' => Hash::make($data['password']),
]);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments