Laravel - Set Selected Option in Dropdown Menu Example
I will explain how to populate select box with selected option dynamically in laravel. You can do it dropdown from database with specific value selected in your html blade file, even if you didn't use Form Class.
we almost use Form Composer package for generate html form. Form facade will help to create text box, radio button, select box etc. you can easily create dynamic select box with Form class. you can make it simply selected value from argument without if condition.
I will give two way to make selected option on drop down menu in laravel. So let's see both example and you can use in your laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 project.
Controller Code:
/**
* Show PDF
*
* @return \Illuminate\Http\Response
*/
public function consentFormListShowPDF(Request $request)
{
$products = Product::pluck('name', 'id');
$selectedID = 2;
return view('stock.edit', compact('id', 'products'));
}
Example 1 Using Form:
<div class="form-group">
{!! Form::Label('product', 'Product:') !!}
{!! Form::select('product_id', $products, $selectedID, ['class' => 'form-control']) !!}
</div>
Example 2 Without Using Form:
<select class="form-control" name="product_id">
<option>Select Product</option>
@foreach ($products as $key => $value)
<option value="{{ $key }}" {{ ( $key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
@endforeach
</select>
I hope it can help you....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Run All Seeders in Laravel?
- Laravel US State Seeder Example
- Laravel Seeder from CSV File Example
- How to Run Specific Seeder in Laravel?
- How to Find Nearest Location using Latitude and Longitude in Laravel?
- Laravel Redirect Back with Input and Error Messages Example
- How to use DB Transactions in Laravel?
- Example of unionAll in Query Builder Laravel
- How to Store Data in Cache in Laravel?
- How to Add Text on Image in Laravel?
- How to Get Query Log in Laravel Eloquent?
- How to Set URL without Http of Other Site in Laravel?