How can I display selected options of a multiple select in this Laravel 8 application?

Updated: Feb 11, 2025

How can I display selected options of a multiple select in this Laravel 8 application?

To display selected options of a multiple select in a Laravel 8 application, you need to pass the selected values from the controller to the view and then display them in the view using Blade syntax. Here's a step-by-step guide on how to achieve this:

  1. In your controller, retrieve the selected values from the request. This assumes you have a form with a multiple select input named options[].
public function store(Request $request)
{
    $selectedOptions = $request->options;

    // Perform other actions here

    return view('yourview', compact('selectedOptions'));
}
  1. In your view file, you can display the selected options using Blade syntax. First, create an empty array to store the selected options.
@extends('layouts.app')

@section('content')
<div>
    Selected options:
    @foreach ($selectedOptions as $option)
        <span>{{ $option }}</span>
    @endforeach
</div>
@endsection
  1. If you want to display the selected options as checkboxes, you can modify the view as follows:
@extends('layouts.app')

@section('content')
<div>
    Selected options:
    @foreach ($options as $option)
        <input type="checkbox" name="options[]" value="{{ $option }}" @if(in_array($option, $selectedOptions)) checked @endif>
        {{ $option }}
    @endforeach
</div>
@endsection

In this example, $options is an array containing all the possible options for the multiple select input. The in_array function is used to check if the current option is in the $selectedOptions array. If it is, the checkbox is checked.

  1. If you want to display the selected options as chips, you can use Laravel's built-in Form::select helper with the multiple option and the old method to display the selected values as chips.
@extends('layouts.app')

@section('content')
<div>
    Selected options:
    {!! Form::select('options[]', $options, old('options'), ['multiple' => true, 'class' => 'form-control select2']) !!}
</div>
@endsection

@section('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('.select2').select2();
    });
</script>
@endsection

In this example, $options is an array containing all the possible options for the multiple select input. The old method is used to display the selected values as chips when the form is submitted and the user navigates back to the page. The Select2 library is used to style the multiple select input as chips.