Search code examples
laraveldropdownmulti-select

How can I edit multi select box in laravel?


BLADE FILE FOR EDIT

<div class="form-group mb-3">
                        <label>Country:</label>
                        <div class="col-sm-4">
                        <select  id="country-dd" name="country[]" class="js-example-basic-multiple form-control" multiple="multiple">
                        @foreach($countries as $country)
                        <option value="{{$country->id }}" {{$country->id == $user->country ? 'selected' : '' }}> {{$country->name}}</option>
                        @endforeach
                        </select>
                    </div>
                    </div>

CONTROLLER

public function edituser(Request $request, $id = null){
        $this->authorize('Admin');
        $userstateid = [];
        $user = new User;
        $user = $user->where('id', $id)->first();
        $countries = Country::get();
        $states = State::get();
        $cities = City::get();
        $roles = Role::get();
        //dd($user);
        return view('edituser',compact('user', 'countries', 'states', 'cities', 'roles'));
    } 

On Edit page, I want to pre-fill select box with user selected countries. Please help me with the same. Thanks in advance


Solution

  • You can use it like this

    <!-- 
    * $countries variable contents all the country name/id
    * $user->country contains all the country id selected by user at the time of creation,
      so it should be an array or json string (if then decode it to array first json_decode())
    -->
    
    <div class="form-group mb-3">
        <label>Country:</label>
        <div class="col-sm-4">
        <select  id="country-dd" name="country[]" class="js-example-basic-multiple form-control" multiple="multiple">
        @foreach($countries as $country)
        <option value="{{$country->id }}" {{is_array($user->country) && in_array($country->id, $user->country) ? 'selected' : '' }}> {{$country->name}}</option>
        @endforeach
        </select>
    </div>
    </div>