Reputation: 91
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?
Upvotes: 0
Views: 75
Reputation: 2730
You can do:
@if(in_array($service->id, $rooms->services->pluck('id')->toArray(), true)) selected @endif
Upvotes: 1
Reputation: 430
Try this at your controller:
$RoomServicesIds = [];
foreach($room->services as $service ){
array_push($RoomServicesIds ,$service->id);
}
Then return $RoomServicesIds
variable with your blade file
In your blade file change the condition to that one:
@if(in_array($service->id,$RoomServicesIds)) selected @endif
Upvotes: 0