Vincent Desrosiers
Vincent Desrosiers

Reputation: 170

Updating pivot table with checkbox

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.

Upvotes: 0

Views: 285

Answers (1)

Mehdi
Mehdi

Reputation: 756

you don't need to iterate the services in your controller. just do this:

$user = Auth::user();
$user->services()->sync($request->services);

this will first clean the pivot table, then will attach the new values all at once.

i really encourage you not to use $request values without validating them. in this case run this before start syncing the pivot table:

$this->validate($request, [
    'services' => 'required|array',
    'services.*' => 'exists:services,id',
]);

Upvotes: 2

Related Questions