I have a users table and a services table. I made a many-many pivot table to store which user offers which services. When I try to check or uncheck a service checkbox in my profile blade to modify the user the data is not inserted or removed in the pivot table.
User Model:
public function services(){
return $this->belongsToMany(Service::class);
}
Service Model:
public function user(){
return $this->belongsToMany(User::class);
}
My code in store function in ProfileController:
$user = Auth::user();
if(isset($request->services)){
foreach($request->services as $service_id){
$service=Service::find($service_id);
$service->user()->syncWithoutDetaching($user->id);
}
}
Blade:
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right">Type de services</label>
<label for="peinture">Peinture</label>
<input type="checkbox" id="peinture" name="services[]" value="1"
<?php if (in_array(1, $services->toArray())) echo "checked" ?> >
<label for="neige">Déneigement</label>
<input type="checkbox" id="neige" name="services[]" value="2"
<?php if (in_array(2, $services->toArray())) echo "checked" ?> >
<label for="gardiennage">Gardiennage</label>
<input type="checkbox" id="gardiennage" name="services[]" value="3"
<?php if (in_array(3, $services->toArray())) echo "checked" ?> >
<label for="entretien">Entretien paysager</label>
<input type="checkbox" id="entretien" name="services[]" value="4"
<?php if (in_array(4, $services->toArray())) echo "checked" ?> >
</div>
If I do dd($request); everything seems in it. No clue what I'm doing wrong, thanks for any help.
syncWithoutDetaching()only adds new IDs but does not remove the existing data. Your code looks okay, just double check if$userhas a user model. I doubt the user might not be logged in.