Home > Back-end >  Adding null on blade's option value in Laravel
Adding null on blade's option value in Laravel

Time:12-06

How do I add a null inside this if else statement because it's throwing Attempt to read property "civil_status_id" on null. What is the proper ternary operator to use so that it will not throw this kind of error if the database table has no value yet. I'll provide the code below

Blade.php file

   <div >
    <div >
     <label for="step1_civilStatus" >Civil Status</label>
      <div >
      <select  type="date" id='civilStatus'   >
      <option>Select Civil Status</option>
      @foreach($statuses as $status)
      @if($status->id > 0)
      @if($user->civil_status_id == $status->id )
       <option value={{$status->id}}  selected>{{$status->complete_name}}</option>                  
      @else
       <option value={{$status->id}}>{{$status->complete_name}}</option>
      @endif
     @endif
    @endforeach
   </select>
  </div>
 </div>
 </div>

CodePudding user response:

$selectedId = $user->civil_status_id ?? null;

You can use this to make it null, and you should also check if it is truly null in the database.

CodePudding user response:

I suppose this is the part that is troubling you:

@if($user->civil_status_id == $status->id )
   <option value={{$status->id}}  selected>{{$status->complete_name}}</option>                  
  @else
   <option value={{$status->id}}>{{$status->complete_name}}</option>
  @endif

You can write it as:

<option value={{$status->id}}  {{$user?->civil_status_id === $status->id ? 'selected' : ''}}>
    {{$status->complete_name}}
</option>

Attempt to read property "civil_status_id" on null is telling you, that $user is null (most likely you have some mistake here...). In this case, $user?->civil_status_id (info) returns null.

  • Related