How to show selected value from database in dropdown using Laravel?

Sarita Sharma picture Sarita Sharma · Jun 21, 2018 · Viewed 20.1k times · Source

I want to show selected value from database into dropdown list on page load.

My controller index function is :

public function index()
{ 
 $country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}

Column name in database for height is :Height

My dropdown in profile_update.blade.php is

<select class="select4" name="country" id="country">
<option value="">Please Select</option>
 @foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id  ? 'selected' : ''}}>{{$country->country_name}}</option>
 @endforeach</select>

Answer

M&#225;rcio Winicius picture Márcio Winicius · Jun 21, 2018

This is a example of how I do this:

<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
        <option value="option_select" disabled selected>Shoppings</option>
        @foreach($shoppings as $shopping)
            <option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id  ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
        @endforeach
    </select>