Sunday, April 2, 2017

Binding pivot table with Laravel Form Builders using checkbox group

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.



via Imran

Advertisement