Search code examples
phplaravel-blade

Laravel: Dropdown field with current value from DB returns NULL if field is left unchanged on update


I have a Laravel Project where you capture an "Operators" info 1 field on form is a dropdown with 3 options. The Capture works perfect. Then i have an option to Edit the Operators info. I use a form to display the current info from DB, all info shows perfect , the dropdown shows the current value, but if i only want to change the "name" for example and not touch anything else, it says the dropdown is NULL, So if i try to edit but this time i change the name and reselect the same current dropdown value it works. Am i using the form correctly?

THIS IS THE DROPDOWN FIELD IN EDIT FORM

<div class="mb-3">
  <label for="exampleFormControlSelect1" class="form-label">
Operator Licence Status</label>
<select name="ol" class="form-select" id="exampleFormControlSelect1">
    <option selected="" disabled="">{{ $types->ol }}</option>
    <option>Available</option>
    <option>Applied</option>
    <option>None</option>
</select>
</div>

THIS IS THE CONTROLLER FUNCTION FOR UPDATE

 public function UpdateOperator(Request $request){
        $pid = $request->id;

         
        Operator::findOrFail($pid)->update([
            'name' => $request->name,
            'id_num' => $request->id_num,
            'address' => $request->address,
            'phone' => $request->phone,
            'email' => $request->email,
            'ol' => $request->ol,
            'ol_number' => $request->ol_number,
            'fees_paid' => $request->fees_paid,
       
            
        ]);

        $notification = array(
            'message' => 'Taxi Operator Updated Successfully',
            'aler-type' => 'success'
        );
        return redirect()->route('view.operator')->with($notification);


    }

if i chose the dropdown values it works and updates the DB


Solution

  • It seems like the issue is related to the way you’re handling the dropdown value in your edit form. The selected option in the dropdown should match the current value from the database for it to work seamlessly when updating. Currently, you’re using an option without a value attribute, which might cause issues.

    <div class="mb-3">
    <label for="exampleFormControlSelect1" class="form-label">Operator Licence Status</label>
    <select name="ol" class="form-select" id="exampleFormControlSelect1">
        <option value="Available" {{ $types->ol === 'Available' ? 'selected' : '' }}>Available</option>
        <option value="Applied" {{ $types->ol === 'Applied' ? 'selected' : '' }}>Applied</option>
        <option value="None" {{ $types->ol === 'None' ? 'selected' : '' }}>None</option>
    </select>