0
votes

I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.

My data model is as follows:

Business
Service
Business_Service table to store many to many link.

Blade Template

@foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
@endforeach

Controller

$service = Service::all();
$selected_services = Auth::user()->business->services()->get();

return view('signup.step2', compact('service', 'selected_services'));

When I return $selected_services I can see the following:

[{"id":2,"name":"Service 1","image":"picture.png","created_at":"2017-03-31 00:31:20","updated_at":"2017-03-31 00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service 2","image":"picture.png","created_at":"2017-03-31 00:31:23","updated_at":"2017-03-31 00:31:23","pivot":{"business_id":103,"service_id":3}}]

I have tried changing $selected_services like this:

$selected_services = Auth::user()->business->services()->keyBy('service_id');

But this only returns one row and doesn't associate a key to the row as expected.

2
One minor point with (in_array($service->id, $selected_services) ? true : false) is that in_array already returns a boolean value, so the ternary is redundant. Use in_array($service->id, $selected_services) instead. - fubar

2 Answers

0
votes

I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.

$service = Service::all();
$business_services = Auth::user()->business->services()->get();

$selected_services = [];
foreach ($business_services as $ss) {
    $selected_services[] = $ss->pivot->service_id;
}

return view('signup.step2', compact('service', 'selected_services'));
0
votes

If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.

$businessServices = Auth::user()->business->services->pluck('id');