Home > Mobile >  Pre-selecting value on edit page with blade in laravel?
Pre-selecting value on edit page with blade in laravel?

Time:05-31

I have an issue where i want to show the current brand in a select, on the edit page of a vehicle mode. The select has to contain all the brands, so it is possible to choose another brand on editing the model.

I have this in my vehicleModelsController edit:

$vehicle_brands = VehicleBrand::all();
        $selected_vehicle_brand = VehicleBrand::first()->vehicle_brand_id;

        return view('vehicleModels.edit', compact(['vehicleModel', 'vehicle_brands'], ['selected_vehicle_brand']));

And in my edit.blade file i have the following select:

<select  name="vehicle_brand_id">
    @if ($vehicle_brands->count())
        @foreach($vehicle_brands as $vehicle_brand)
            <option value="{{ $vehicle_brand->id }}" {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }}>
                {{ $vehicle_brand->brand }}</option>
        @endforeach
    @endif
</select>

And it works just fine with editing, but it does not show the current value as selected, it shows the first value in the brand table.

I have Brand1, Brand2, Brand3 and Brand4 as test values in the brand table, but no matter what brand the model is related to, it shows Brand1 in the select on the edit page.

Any help is greatly appreciated!

CodePudding user response:

In the controller you are assigning value of VehicleBrand::first()->vehicle_brand_id to $selected_vehicle_brand and then you are comparing it with id field in {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }}

If there is not column/field named vehicle_brand_id on VehicleBrand model then VehicleBrand::first()->vehicle_brand_id will be null. So when you compare $selected_vehicle_brand == $vehicle_brand_id it will be like null == $vehicle_brand->id which will be false for any id value.

So it should either be (in Controller)

$selected_vehicle_brand = VehicleBrand::first()->id;
//Here we are hard coding the value to be the id of first record of VehicleBrand
//However in practice it should come from either request/route param eg: $id received via the request/route param
//Or from VehicleModel being edited eg: $vehicleModel->vehicle_brand->id

And {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }} in the view

Or, if vehicle_brand_id column/field exists on VehicleBrand, it should be (in Controller)

$selected_vehicle_brand = VehicleBrand::first()->vehicle_brand_id;

and {{ $selected_vehicle_brand == $vehicle_brand->vehicle_brand_id ? 'selected="selected"' : '' }}

The field you are comparing the values for should be the same.

And as a side note, if you are on Laravel 9 you can use @selected blade directive @selected(old($vehicle_brand->id) == $selected_vehicle_brand)

  • Related