Search code examples
phplaraveleloquenteloquent-relationship

How to display attached values as selected in Laravel?


I'm using many to many relationship in laravel 8. Have two models: Room and Service. I have attached some services to a specific room and now, when I want to edit this specific room I need it to show me which services are selected and which are not.

This is a code I am using:

<select class="form-select" name="service_id[]" id="service_id" multiple>
    @foreach($services as $service)
    <option value="{{ $service->id }}" @if($rooms->services->in_array()) selected @endif>{{ $service->name }}</option>
    @endforeach
</select>

Any suggestions?


Solution

  • You can do:

    @if(in_array($service->id, $rooms->services->pluck('id')->toArray(), true)) selected @endif