Home > Net >  How to display the pivot value in multi select2 in Laravel?
How to display the pivot value in multi select2 in Laravel?

Time:11-29

How to display the pivot value in multi select2 in Laravel?

In my controller

$appointment = Appointment::with('services')->where('id', $id)->first();

This is the output

enter image description here

In my blade, I want to display the pivot table value service_id in multi select2. Currently I have two records in my pivot

enter image description here
this my blade

@foreach ($service as $item)
     <option value="{{ $item->id }}"
        {{ in_array($item->id, $appointment->pivot_should_be_here ?: []) ? 'selected' : '' }}>
        {{ $item->name }}</option>
@endforeach

CodePudding user response:

Try this in your controller, you have to convert this values into Array, and then you can pass this to your blade.

$appointment = Appointment::with('services')->where('id', $id)->first();
$app = $appointment->services->pluck('id')->toArray();

Then in your blade

@foreach ($service as $item)
    <option value="{{ $item->id }}"
        {{ in_array($item->id, $app ?: []) ? 'selected' : '' }}>
        {{ $item->name }}</option>
@endforeach
  • Related