Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vinschi's avatar
Level 16

Select Multiple Input

Hi guys, I need a small help. I have a booking form where I can choose more than one accessory. My input is defined in this way:

<div class="col-md-12">
    <div class="form-group">
        <label class="control-label" for="accessories">Choose your Accessories</label>
        <select name="accessory_id" class="form-control" multiple="multiple">
            @foreach($accessories as $accessory)
                <option value="{{$accessory->id}}">{{$accessory->name}}</option>
            @endforeach
        </select>
    </div>
</div>

when I select more than one accessory I have an "Array to string conversion" error.

By the way the relationships are defined in this way:

Booking.php

public function accessories()
    {
        return $this->hasMany(Accessory::class);
    }

Accessory.php

public function bookings()
    {
        return $this->belongsToMany(Booking::class);
    }

meaning that a booking can have more than one accessory and an accessory can belong to many bookings.

Any ideas? Thanks

0 likes
5 replies
Cronix's avatar

try changing the name of your select element to name="accessory_id[]" adding the brackets at the end, which will tell PHP it's an array.

Then just know that $request->accessory_id will be an array in your controller.

vinschi's avatar
Level 16

Hi @Cronix thanks for the answer. What do you mean in the controller? When I'm creating an instance of the booking do I have to use the attach method in this way?

$booking->accessories()->attach($request('accessory_id'));

Thanks,

Cronix's avatar

By controller, I mean the controller that the form submits to where you process the data to store.

vinschi's avatar
Level 16

Yes @Cronix , my booking controller. So to add more than one accessory id to the booking I have to use the attach method as I posted it, am I right?

Cronix's avatar

Yes, either attach() or sync(), depending on what you're trying to accomplish

Please or to participate in this conversation.