Laravel select2 set selected option on blade file

Solution:

there are a lot of ways to do this let’s start with the simplest one I will suppose we have companies’ array

$companies = ['google', 'facebook', 'amazon'];
$selectedCompany = 1;

1- you can just select the equivalent key

<option value="{{$key}}" {{ ($key === $selectedCompany) ? 'selected' : '' }}>{{$value}}</option>

2- you can use Components to build Option Component https://laravel.com/docs/8.x/blade#components

from CLI run

php artisan make:component Forms/Select/Option

laravel will create two files one for the view code and the second for the logic

resources/views/components/forms/select/option.blade.php
app/View/Components/Forms/Select/Option.php

create three properties $key, $value and $selectedKey

<?php

namespace App\View\Components\Forms\Select;

use Illuminate\View\Component;

class Option extends Component
{
    public $value;

    public $key;

    public $selectedKey;
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($key, $value, $selectedKey)
    {
        $this->key = $key;
        $this->value = $value;
        $this->selectedKey = $selectedKey;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.forms.select.option');
    }
}

and the option.blade.php content

<option value="{{$key}}" {{ $key === $selectedKey ? 'selected' : '' }}>{{$value}}</option>

now you can call this component wherever you want and pass it the properties

<x-forms.select.option :value="$value" :key="$key" :selectedKey="$selectedCompany"> </x-forms.select.option>

3- you can use laravelcollective/html package https://laravelcollective.com/docs/6.x/html#drop-down-lists

form the CLI run

composer require laravelcollective/html

now you can use the Form::select in any blade view file

{{ Form::select('company_id', $companies, $selectedCompany) }}

I hope it’s helpful