[php] Setting selected option in laravel form

I need to give selected value like this html:

<select name="myselect" id="myselect">
 <option value="1">Item 1</option>
 <option value="2" selected='selected'>Item 2</option>

how can I achieve this, with laravel forms?

This question is related to php laravel laravel-5.2

The answer is


You can do it like this.

<select class="form-control" name="resoureceName">

  <option>Select Item</option>

  @foreach ($items as $item)
    <option value="{{ $item->id }}" {{ ( $item->id == $existingRecordId) ? 'selected' : '' }}> {{ $item->name }} </option>
  @endforeach    </select>

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.


  <?php
      $items = DB::table('course')->get()->pluck('name','id');
      $selectID = 3;
  ?>

  <div class="form-group">
   {{ Form::label('course_title', 'Course Title') }}
   {!! Form::select('myselect', $items, $select, ['class' => 'form-control']) !!}
  </div>

This show similar types of following options :

<select name="myselect" id="myselect">
 <option value="1">Computer Introduction</option>
 <option value="2">Machine Learning</option>
 <option value="3" selected='selected'>Python Programming</option>
 <option value="4">Networking Fundamentals</option>
 .
 .
 .
 .  
</select>

Just Simply paste this code you will get the desired output that you needed.

 {{ Form::select ('myselect', ['1' => 'Item 1', '2' => 'Item 2'], 2 , ['id' =>'myselect']) }}` `

You can also try this for limited options:

          <select class="form-control required" id="assignedRole">
            <option id = "employeeRole" selected ="@if($employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
            <option id = "adminRole" selected ="@if($employee->employee_role=='Admin'){'selected'}else{''} @endif">Admin</option>
            <option id = "employerRole" selected ="@if($employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
          </select>

Try this

<select class="form-control" name="country_code" value="{{ old('country_code') }}">
   @foreach (\App\SystemCountry::orderBy('country')->get() as $country)
       <option value="{{ $country->country_code }}"
           @if ($country->country_code == "LKA")
             {{'selected="selected"'}}
           @endif
       >
          {{ $country->country }}
       </option>
   @endforeach
</select>

To echo some other answers here, the code I just used with 5.6 is this

{{ Form::select('status', ['Draft' => 'Draft', 'Sent' => 'Sent', 'Paid' => 'Paid'], $model->status, ['id' => 'status']) }}

In order to be able to use the Form Helper from LaravelCollective I took a look at https://laravelcollective.com/docs/master/html#drop-down-lists

I also had to composer require the dependency also so that I could use it in my projects

composer require "laravelcollective/html":"^5"

Lastly I altered my config/app.php and added the following in the $aliases array

    'Form' => Collective\Html\FormFacade::class,

https://laravelcollective.com/docs/master/html should be consulted if any of the above ceases to work.


Setting selected option is very simple in laravel form :

{{ Form::select('number', [0, 1, 2], 2) }}

Output will be :

<select name="number">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
</select>

Another ordinary simple way this is good if there are few options in select box

<select name="job_status">
   <option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}}  value="unemployed">Unemployed</option>
   <option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>
</select>

You have to set the default option by passing a third argument.

{{ Form::select('myselect', [1, 2], 2, ['id' => 'myselect']) }}

You can read the documentation here.


If you have an Eloquent Relationship between your models you can do something like that:

@foreach ($ships as  $ship)
<select name="data[]" class="form-control" multiple>
    @foreach ($goods_containers as  $container)
        <option value="{{ $container->id }}"
                @if ($ship->containers->contains('container_id',$container->id ) ))
                selected="selected"
                @endif
        >{{ $container->number}}</option>
    @endforeach
</select>
@endforeach

If anyone is still here, here is my simple version.

<select name="status" class="js-example-basic-single w-100">
              <option value="" @if($brand->status == '') ? selected : null @endif disabled>Choose what to be seen on brand section</option>
              <option value="TA" @if($brand->status == 'TA') ? selected : null @endif>Title Active</option>
              <option value="ITA" @if($brand->status == 'ITA') ? selected : null @endif>Image Title Active</option>
             
            </select>

            @foreach ($categories as $category)
             <option value="{{$category->id}}" 
               @foreach ($posts->postRelateToCategory as $Postcategory)
                 @if ($Postcategory->id == $category->id)
                 {{'selected="selected"'}}
                 @endif 
               @endforeach >
              {{ $category->category_name }} </option>               
            @endforeach    

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-5.2

How to uninstall an older PHP version from centOS7 Extension gd is missing from your system - laravel composer Update How to fix error Base table or view not found: 1146 Table laravel relationship table? Setting selected option in laravel form How to clear Route Caching on server: Laravel 5.2.37 Where are logs located? Laravel 5.2 redirect back with success message getting error while updating Composer How to validate phone number in laravel 5.2? Laravel check if collection is empty