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

Vusumzi's avatar

how to Extract Checkbox values from the Database to be updated in view

I am trying to update the checkbox values stored in the database but I can't get them to the update view form

Here is my update method in UserController

 public function update(Request $request, $id)
    {
        $this->validate($request,[
            'email' => 'email',
            'phone' => 'min:10|max:15',
            'gender' => 'required',
            'identity' => 'required',
            'password' => 'string|min:8|confirmed',
            'street' => 'required',
            'suburb' => 'required',
            'city' => 'required',            
            'province' => 'required|not_in:0',
            'code' => 'required',
            'school' => 'required',
            'grade' => 'required|not_in:0',
            'subjects' => 'required'
        ]);
    
        $user = User::find($id);
        
        $user->update($request->all());

           if($user->types == 'Learner'){
            $learner = Learner::where('user_id', $id)->first();
            $learner->gender = $request->input('gender');
            $learner->identity = $request->input('identity');
            $learner->street = $request->input('street');
            $learner->suburb = $request->input('suburb');
            $learner->city = $request->input('city');
            $learner->province = $request->input('province');
            $learner->code = $request->input('code');
            $learner->school = $request->input('school');
            $learner->grade = $request->input('grade');
            $learner->subjects = $request->input('subjects');            
            $learner->save();
            return redirect()->back()->with('message', 'User Updated Successfully');
           }

My Learner Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
// use App\User;

class Learner extends Model //class Learner extends User
{
    protected $guarded = [];
    protected $table = "learners";
    protected $casts = [
        'subjects' => 'array',
    ];
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function setSubjects($value)
    {
        $this->attributes['subjects'] = json_encode($value);
    }

    public function getSubjects($value)
    {
        return $this->attributes['subjects'] = json_decode($value);
    }
}

edit.blade.php

<div class="col-md-2 font-weight-bold pt-2">Subjects:</div>
                            <div class="col-md-10">                            
                                <div class="form-group">
                                    <div class="custom-control custom-checkbox mt-2">
                                        <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="Mathematics" name="subjects[]" value="Mathematics" @foreach($user as $subject) {{ ($user->learner->subjects=='Mathematics') ? 'checked' : '' }} @endforeach/>
                                        <label class="custom-control-label" for="Mathematics">Mathematics</label>
                                    </div>
                                    <div class="custom-control custom-checkbox mt-2">
                                        <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="Physical Science" name="subjects[]" value="Physical Science" {{ ($user->learner->subjects=='Physical Science')? 'checked' : '' }}/>
                                        <label class="custom-control-label" for="Physical Science">Physical Science</label>
                                    </div>
                                    <div class="custom-control custom-checkbox mt-2">
                                        <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="Accounting" name="subjects[]" value="Accounting" {{ ($user->learner->subjects=='Accounting')? 'checked' : '' }}/>
                                        <label class="custom-control-label" for="Accounting">Accounting</label>
                                    </div>
                                    <div class="custom-control custom-checkbox mt-2">
                                        <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="Life Science" name="subjects[]" value="Life Science" {{ ($user->learner->subjects=='Life Science')? 'checked' : '' }}/>
                                        <label class="custom-control-label" for="Life Science">Life Science</label>
                                    </div>
                                    <div class="custom-control custom-checkbox mt-2">
                                        <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="Geography" name="subjects[]" value="Geography" {{ ($user->learner->subjects=='Geography')? 'checked' : '' }}/>
                                        <label class="custom-control-label" for="Geography">Geography</label>
                                    </div>
                                @error('subjects')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                                </div>
                            </div>

and when I try to loop the values in the show method it gives an error

show.blade.php

<tr>
        <th scope="row">Subjects</th>
               <td> 
                      @foreach($user->subjects as subject)                                  
                            {{ subjects }}
                       @endforeach
              </td>
</tr>                                	

and in my database the checkbox values are stored stored like this:

subjects: ["Mathematics","Physical Science","Accounting"]
0 likes
6 replies
newbie360's avatar

missing $

@foreach($user->subjects as $subject)                                  
                            {{ $subject }}
                       @endforeach
Vusumzi's avatar

Yes I noticed that but still it shows this error:

Invalid argument supplied for foreach() (View: C:\xampp\htdocs\laravel-sb\resources\views\backend\user\show\learner.blade.php)

a4ashraf's avatar

@vusumzi

try like this


// pass this from your controller

$subjects = ['Mathematics', 'Physical Science', 'Accounting', 'Life Science', 'Geography'];
$userSubject = $user->learner->subjects;



// and create your blade component  like this 

	<div class="col-md-2 font-weight-bold pt-2">Subjects:</div>
        <div class="col-md-10">                            
            <div class="form-group">
            	@foreach($subjects as $subject) 
	                <div class="custom-control custom-checkbox mt-2">
	                    <input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" id="{{ $subject }}" name="subjects[]" value="{{ $subject }}" {{ in_array($subject, $userSubject)) }} />
	                    <label class="custom-control-label" for="{{ $subject }}">{{ $subject }}</label>
	                </div>
	            @endforeach
	            @error('subjects')
	                <span class="invalid-feedback" role="alert">
	                    <strong>{{ $message }}</strong>
	                </span>
	            @enderror
            </div>
        </div>
    </div>
1 like
newbie360's avatar

you can try debug

{{ dd($user->subjects) }}

@foreach($user->subjects as $subject)  

i haven't read all the code!!

    protected $casts = [
        'subjects' => 'array',
    ];

this is something wrong ? this look like Mutator ? but

https://laravel.com/docs/7.x/eloquent-mutators#defining-a-mutator

    public function setSubjects($value)
    {
        $this->attributes['subjects'] = json_encode($value);
    }
1 like
Snapey's avatar
Snapey
Best Answer
Level 122

In the edit view you need to again show checkboxes according to all possible values - not the ones that the user selected before.

Then as you present each checkbox, you need to see if the user's subjects array contains the current checkbox value. If it is then that checkbox is selected.

<input type="checkbox" class="custom-control-input @error('subjects') is-invalid @enderror" 
    id="Mathematics" name="subjects[]" 
    value="Mathematics" 
    {{ in_array('Mathematics', $user->learner->subjects) ? 'checked' : '' }} />

you don't need to foreach on their previous choices.

1 like
Snapey's avatar

This version remembers the user's choice if there is a validation error

{{ in_array('Mathematics', old('subjects', $user->learner->subjects)) ? 'checked' : '' }} />
1 like

Please or to participate in this conversation.