Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saadat_2003's avatar

How to delete unchecked checkboxes in laravel

I have displayed checkboxes of subjects in laravel.In which some checkboxes are already checked ,come from database.When any checkbox is checked the new subject is added in database. The actual problem is that there are other subjects checkboxes that are not saved in database. The issue to resolve is that,when user uncheck any checkbox of subject which is saved in database should be deleted from database

In blade

@foreach($grades as $grade) {{$grade->name}}
    @foreach($grade->subject as $subject)
  • {!!Form::checkbox('check_list[]',$grade->id.'-'.$subject->id,$yes,['class'=>''])!!} {{$subject->name}}
  • @endforeach
@endforeach

in Controller

if($request->check_list){ $user_id = auth()->user()->id; $i = 0; $j = 0;

                foreach ($request->check_list as $data) {
                    $array1[$i] = explode('-', $data);
                    $i++;
                }
                foreach ($array1 as $j => $data1) {

                    $hasSubject = UserSubject::where('user_id', $user_id)->where('subject_id', $data1[1])->where('grade_id', $data1[0])->first();

                    if(is_null($hasSubject)) {

                        $user_subjects = new UserSubject();
                        $user_subjects->user_id = $user_id;
                        $user_subjects->grade_id = $data1[0];
                        $user_subjects->subject_id = $data1[1];
                        $user_subjects->status = 1;
                        $user_subjects->created_at = date("Y-m-d H:i:s");
                        $user_subjects->updated_at = date("Y-m-d H:i:s");
                        // dd($user_subjects);
                        $user_subjects->save();

                        $j++;
                    }
                }
0 likes
2 replies
grenadecx's avatar

You could make the UserSubjects into a pivot table and use the relation belongsToMany.

User model

public function subjects()
{
    return $this->belongsToMany(Subjects::class, 'pivot_table_name');
}

This way, you could just use the sync function in eloquent, which will delete those that aren't in the $subjects array:

$user->subjects()->sync($subjects)

If you want to keep the current structure, take a look at the answer over here:

https://laracasts.com/discuss/channels/laravel/how-can-i-add-a-new-item-in-one-to-many-relation-while-updating

Please or to participate in this conversation.