Search code examples
laravellaravel-8laravel-ui

Undefined array key "name_of_firm" in laravel?


This is my RegisterController (Laravel ui edited). please help me. Is i have to add any other page to this question.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\Models\User
 */
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'name_of_firm' => $data['name_of_firm'],
        'number' => $data['number'],
        'address' => $data['address'],
    ]);
}

enter image description here


Solution

  • There is 2 case if name_of_firm is nullable or required

    Case : 1

    if name_of_firm is required

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'name_of_firm' => ['required']
        ]);
    }
    
    
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'name_of_firm' => $data['name_of_firm'],
            'number' => $data['number'],
            'address' => $data['address'],
        ]);
    }
    
    

    Case : 2

    if name_of_firm is nullable

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
    
    
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'name_of_firm' => $data['name_of_firm'] ?? null, // make sure database is accept null value
            'number' => $data['number'],
            'address' => $data['address'],
        ]);
    }