简体   繁体   中英

How to get the country value based on the country code?

This code " $countries = Facades\\Countries::all(); " returns the country code and code value like:

  "DE" => "Germany"

I want to store the user country in the db when the user select the country in a select menu

 <div class="form-group">
    <label for="country" class="text-gray">Country</label>
    <select class="form-control" name="country" id="country">
        @foreach($countries as $key => $country)
            <option value="{{$key}}">{{$country}}</option>
        @endforeach
    </select>
</div>

But with:

$user->country = $request->country;
$user-save();

In the db is stored "DE" but I want to store the country value like "Germany". Do you know how to based on the country code get the value so is possible to store the value and not the code?

In the db is stored "DE" but I want to store the country value like "Germany".

You just need to use as:

$countries = Facades\Countries::all();
$user->country = $countries[$request->country];

Just make sure that Facades\\Countries::all() does not have performance impact, i guess it pulls out data from db.

OR

Other solution is to remove value attribute from option tag.

<option>{{$country}}</option>

try this, replace {{$key}} with {{$country}} in option

<div class="form-group">
    <label for="country" class="text-gray">Country</label>
    <select class="form-control" name="country" id="country">
        @foreach($countries as $key => $country)
            <option value="{{$country}}">{{$country}}</option>
        @endforeach
    </select>
</div>

Place country name in select options value as well. Replace {{$key}} with {{$country}} :

@foreach($countries as $country)
    <option value="{{$country}}">{{$country}}</option>
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM