How to Set Select Box Selected Option In Laravel Blade

In this tutorial you will learn How to Set Select Box Selected Option value if user edit their record In Laravel. More then times we need selected option value in select box and when user update the record if validation occur other field then the old value retain.

If you have same issue you check this article here we have already special old value maintain with selected values of select box. So, here you can set the selected options of select box easily in laravel blade file. This example explain laravel select option selected from database with keep the old value.

Set Selected Option Select Box Dropdown in Laravel

In the plan Html we can use something like;

In Controller

Here we just specify the code how can the values comes from controller. We show countries dropdown and save one country to user table. If the user comes in edit form then we show him/her selected values which he already selected before.

    public function edit($id)
    {
        $user = User::findOrFail($id);
        $countries = Country::all();

        return view('backend.dashboard.users.edit', compact('countries', 'user'));
    }

In Blade File

Now the counties loop running laravel blade file and the option value comes from user table and we match the record which are same then the option selected see below code.

<div class="form-group">
    <strong>Country:</strong>
    <select name="country" class="form-control custom-select">
      <option value="">Select Country</option>
      @foreach($countries as $country)
        <option value="{{ $country->id }}" @if($country->id == $user->country) selected @endif>{{ $country->name }}</option>
      @endforeach
    </select>
</div>

Selected Value with Old Value Retain on Update

Many times we need to maintain the old value with selected option when we update the record and other fields has occur any validation.

<div class="form-group">
    <strong>Country:</strong>
    <select name="country" class="form-control custom-select">
      <option value="">Select Country</option>
      @foreach($countries as $country)
        <option value="{{ $country->id }}" @if(old('country') == $country->id || $country->id == $user->country) selected @endif>{{ $country->name }}</option>
      @endforeach
    </select>
</div>

If you not using the plan html then you can use somethig like:

{!! Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S'); !!}

Retain Old value in multiple select option in laravel

How to Use Select 2 Dropdown in Laravel for Multiple Select

I hope this example help you. If you have any question and want to something else from us please comment below or you can send contact us via contact us page. Have a great day!!

4 thoughts on “How to Set Select Box Selected Option In Laravel Blade”

Leave a Comment