Search code examples
laravellaravel-blade

Laravel 11 Blade component for select with array


I'm pretty new to Laravel and I've created a blade component for displaying selection components but I'm getting the following error when the page is rendered.. The attributes merge is causing the problem as I've hard coded it and it displays the select component with all options. It sounds like it's trying to render the array in the select line to me?? Any help would be greatly appreciated..

*I can see the same issue was raised a few years ago but surely there's a better solution/fix by now?

Sending arrays to Blade component (Laravel 8)

TypeError trim(): Argument #1 ($string) must be of type string, array given

This is how i invoke the component

<x-form-select id="club_id" name="club_id" :options="$clubs" />

This is the blade component:

<div class="mt-2">
    <select {{ $attributes->merge(['class'=>'block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs sm:text-sm sm:leading-6']) }}>
        @foreach ($options as $key => $value)
            <option value="{{ $key }}" @selected(old('class_id') == $key)>{{ $value }}</option>
        @endforeach
    </select>
</div>

This is the array

$clubs = [ "-" => "", "1" => "Blah Hockey Club", "2" => "Another Hockey Club", "3" => "A University", "4" => "A School" ];


Solution

  • It seems like your $clubs does not contain proper data, component looks fine. Your $clubs should have a key-value pair.

    Edit: I found the mistake. You forgot to catch the props within your component. @props(['options']) add this to the top of your file.

    @props(['options'])
    <div class="mt-2">
        <select
            {{ $attributes->merge([
                'class' =>
                    'block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs sm:text-sm sm:leading-6',
            ]) }}>
            @foreach ($options as $key => $value)
                <option value="{{ $key }}" @selected(old('class_id') == $key)>{{ $value }}</option>
            @endforeach
        </select>
    </div>