phphtmllaravellaravel-blade

How to use isset in select option in laravel form


How to use isset if i use select option? Please help.

This is how i use to get my data for normal insert.

<div class="form-group">
  <label>Zone Name</label>
  <input type="text" name="name" class="form-control" value="{{ old('name',isset($zone) ? $zone->name : '') }}" placeholder="Name">
</div>

But i don't know how to use isset in select option.

<div class="form-group">
  <label>Select Country</label>
  <select class="form-control" name="country_id">
    <option value="" selected>Please Select</option>
      @if ($country->count())
        @foreach($country as $c)
          <option value="{{ $c->country_id }}" {{ $selectCountry == $c->country_id ?  : '' }}>{{ $c->name }}</option>
        @endforeach
      @endif
  </select>
</div>  

This is my Controller

  public function edit(Request $request, $id){
    $zone = Zone::find($id);
    $country = Country::all();
    $selectCountry= Country::first()->country_id;
    if(!$zone){
      return redirect('/');
    }
    return view('zone.edit',['zone' => $zone, 'country'=>$country, 'selectCountry'=>$selectCountry]);
  }

my expected result is when i press on edit button, it will show the previous selected result.


Solution

  • You can write

    <select class="form-control" name="country_id">
         <option value="" {{ !isset($selectCountry) ? 'selected' : '' }}>Please Select</option>
        @if ($country->count())
          @foreach($country as $c)
           <option value="{{ $c->country_id }}" {{ (isset($selectCountry) && $selectCountry == $c->country_id) ? 'selected' : '' }}>{{ $c->name }}</option>
          @endforeach
        @endif
     </select>