How to Fix Undefined index Issue

What seems to be the problem:
I have a form in a livewire view, one of the input fields (Middle Name) is nullable, however when I try to submit the form and I don’t fill that input field I usually would get the error **Undefined index: middle_name **, but when the Middle Name Input field is filled I get no error.

HOW I TRIED TO SOLVE IT

I read through the internet and I realized that the issue was caused by wire: model .defer =‘middle_name’ which I removed the .defer Like this. This worked until I tried to define accessors in my model, which I used to fix the error message. However when I added the FullNameAttributes in my model I noticed the error popped up again.

public function setMiddleNameAttribute($value)

{

    if ($value) {

        $this->attributes['middle_name'] = ucfirst(strtolower($value));

    }

THIS IS MY ENTIRE VIEW

    @csrf

    <div class="row">

        <div class="col-md-6 mb-1">

            <label for="first_name" class="form-label">FirstName</label>

            <input type="text" name="first_name"

                class="form-control @error('state.first_name') is-invalid @enderror" placeholder=""

                aria-label="First Name" wire:model.defer="state.first_name" autofocus>

            @error('state.first_name')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

        <div class="col-md-6 mb-1">

            <label for="middle_name" class="form-label">MiddleName</label>

            <input type="text" name="middle_name"

                class="form-control @error('state.middle_name') is-invalid @enderror" placeholder=""

                aria-label="Middle name" wire:model="state.middle_name">

            @error('state.middle_name')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

    </div>

    <div class="row">

        <div class="col-md-6 mb-1">

            <label for="last_name" class="form-label">LastName</label>

            <input type="text" name="last_name" class="form-control @error('state.last_name') is-invalid @enderror"

                placeholder="" aria-label="Last name" wire:model.defer="state.last_name">

            @error('state.last_name')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

        <div class="col-md-6 mb-1">

            <label for="email" class="form-label">Email</label>

            <input type="email" name="email" class="form-control @error('state.email') is-invalid @enderror"

                placeholder="" aria-label="Email" wire:model.defer="state.email">

            @error('state.email')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

    </div>

    <div class="row">

        <div class="col-md-6 mb-1">

            <label for="phone_number" class="form-label">Phone Number</label>

            <input type="text" name="phone_number"

                class="form-control @error('state.phone_number') is-invalid @enderror" placeholder=""

                aria-label="Phone Number" wire:model.defer="state.phone_number">

            @error('state.phone_number')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

        <div class="col-md-6 mb-1">

            <label for="designation" class="form-label">Designation</label>

            <input type="text" name="designation"

                class="form-control @error('state.designation') is-invalid @enderror" placeholder=""

                aria-label="Designation" wire:model.defer="state.designation">

            @error('state.designation')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

    </div>

    <div class="row">

        <div class="col-md-12 mb-1">

            <label for="state.grade_level_id" class="form-label">Grade Level/Step</label>

            <select name="state.grade_level_id"

                class="form-select @error('state.grade_level_id') is-invalid @enderror" aria-label="grade_level_id"

                required autofocus wire:model="state.grade_level_id">

                <option value="">select gl/s</option>

                @foreach ($grade_level_steps as $gl_s)

                    <option value="{{ $gl_s->id }}">{{ $gl_s->gradelevel_step }}</option>

                @endforeach

            </select>

            @error('state.grade_level_id')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

    </div>

    <div class="row">

        <div class="mb-2 col-md-12">

            <label for="address" class="form-label">Address</label>

            <textarea name="address" class="form-control @error('state.address') is-invalid @enderror" id="address"

                rows="3" wire:model.defer="state.address"></textarea>

            @error('state.address')

                <span class="invalid-feedback" role="alert">

                    <strong>{{ $message }}</strong>

                </span>

            @enderror

        </div>

    </div>

    <div class="pb-6 pt-4">

        <a name="" id="" class="btn btn-success float-right" href="#" role="button"

            wire:click.prevent="submit">Next</a>

    </div>

</form>

strong text
public $state = [];

protected $rules = [

    'state.first_name' => 'required',

    'state.middle_name' => 'nullable',

    'state.last_name' => 'required',

    'state.designation' => 'required',

    'state.grade_level_id' => 'required',

    'state.phone_number' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

    'state.email' => 'required|email|unique:staffrecords,email',

    'state.address' => 'required',

];

public function store()

{

    try {

        DB::transaction(

            function () {

                $staffrecs = Staffrecord::create([

                    'staff_id' => '',

                    'first_name' => $this->state['first_name'],

                    'middle_name' => $this->state['middle_name'],

                    'last_name' => $this->state['last_name'],

                    'designation' => $this->state['designation'],

                    'grade_level_id' => $this->state['grade_level_id'],

                    'phone_number' => $this->state['phone_number'],

                    'email' => $this->state['email'],

                    'address' => $this->state['address'],

                ]);

                           }

        );

        session()->flash('success', 'Staff Created Succussfully');

        return redirect()->route('dashboard');

    } catch (\Exception $e) {

        session()->flash('error', $e->getMessage());

        return redirect()->route('dashboard');

    }

}

MY MODEL

protected $fillable =

[

    'staff_id', 'first_name', 'middle_name', 'last_name', 'designation',

    'grade_level_id', 'phone_number', 'email', 'address'

];

/* Defination of all Attributes  for staff Records Using Accessors*/

public function setFirstNameAttribute($value)

{

    $this->attributes['first_name'] = ucfirst(strtolower($value));

}

public function setLastNameAttribute($value)

{

    $this->attributes['last_name'] = ucfirst(strtolower($value));

}

public function setMiddleNameAttribute($value)

{

    if ($value) {

        $this->attributes['middle_name'] = ucfirst(strtolower($value));

    }

}

public function getFullNameAttribute()

{

    return

        sprintf(

            '%s %s %s',

            $this->first_name,

            $this->middle_name,

            $this->last_name

        );

}

Hey, @captainsesman

You can check if there is a middle name in various ways, and it’s a Laravel issue or to be specific it’s an PHP error and there is nothing related to Livewire here.

First:

Try to check if there is a middle_name Like this:

if (isset($this->attributes['middlename']) {
  //
}

Second:

use a null operator:

 'middle_name' => $this->state['middle_name']  ?? null,

Third:

Make a default value of middle_name

public $state = [
 'middle_name' = null,
];

Forth:

In the migration file make the middle_name nullable by default

$this->string('middle_name')->nullable();
1 Like

Thanks for the Many Options… Lord Skywalker :crazy_face:
I used the second option and it works fine.
Gracia

OH! I’m glade that worked

Happy coding mate!