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

dr24's avatar
Level 2

Problem with storing checkbox values in database

I am trying to store my checkbox values in database. I have these three tables.

fields

id    name
1     gender
2     looking_for

field_values (here field_id references id on fields table)

id    field_id    value    label
1        1          1      Men
2        1          2      Women
3        2          3      Relationship
4        2          4      Friendship
5        2          5      Marriage

user_interests (here field_id references field_id on field_values table and value_id references value on field_values table)

user_id    field_id    value_id
1          1           2
1          2           4
1          2           5

gender in blade uses option values and looking_for uses checkbox values. I made one function that is trying to update both of them. I use two foreaches in my function and I am able to successfully update gender option, but I am unable to update looking_for option. When I click submit button nothing happens, also when I dump anything inside that foreach that is supposed to update checkboxes it doesn't dump. Any help is greatly appreciated. Here is my code.

web.php

Route::patch('profile/interests', 'UserProfileController@updateInterestsData')->name('profile.update.interests.data');

UserProfileController.php

public function updateInterestsData(UpdateInterestsDataRequest $request)
{
    $user = User::with('userProfile')->where('id', Auth::user()->id)->firstOrFail();

    $request->validated();

    $userId = $request->input('user_id') ? $request->input('user_id') : Auth::user()->id;

    $data = $request->all();
    $options = [
        'gender'         => 1,
        'looking_for'    => 2
    ];

    foreach ($options as $fieldName => $fieldId) {
        if (! empty($data[$fieldName])) {
            DB::table('user_interests')
                ->where('user_id', $userId)
                ->where('field_id', $fieldId)
                ->delete();

            if (is_array($data[$fieldName])) { // CHECKBOX FIELDS AND HERE IT DOESN'T WORK!!!
            //dd('DIE!!!!!!') IT DOESN'T ENTER HERE!!!
                foreach ($data[$fieldName] as $key => $value) {
                    DB::table('user_interests')->insert([
                        'user_id'  => $userId,
                        'field_id' => $fieldId,
                        'value_id' => $value
                    ]);
                }
            } else { // SELECT FIELDS!!!
                DB::table('user_interests')->insert([
                    'user_id'  => $userId,
                    'field_id' => $fieldId,
                    'value_id' => $data[$fieldName]
                ]);
            }
        }
    }

    $user->userProfile->update(
        [
            'age_from_preference' => $request->age_from_preference,
            'age_to_preference' => $request->age_to_preference,
            'updated_at' =>  Carbon::now()
        ]
    );

    $request->user()->save();

    return redirect()->route('profile.show', [$user->username]);
}

index.blade.php

<form action="{{ route('profile.update.interests.data') }}" method="POST" class="flex">
    @method('PATCH')
    @csrf
    <div class="form-group">
        <span>Interessiert an</span>
        {{-- wrong value - selected --}}
        @isset($options)
            @foreach($options as $name => $fieldData)
                @if ($name == 'gender')
                    <div class="selectHolder">
                        <select name="{{ $name }}">
                            <option selected="true" disabled="disabled" value="" style="display:none">bitte auswählen</option>
                            @foreach($fieldData['data'] as $value => $label)
                                <option value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'selected' : '') : '' }}>
                                    {{ $label }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <?php
                        unset($options[$name]);
                    ?>
                @endif
            @endforeach
        @endisset
    </div>
    <div class="form-group">
        <span>Im Alter von</span>
        <input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_from_preference ?? "" }}" name="age_from_preference">
        <span>Jahren bis</span>
        <input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_to_preference ?? "" }}" name="age_to_preference">
        <span>Jahren</span>
    </div>
    {{-- wrong value - checked --}}
    @isset($options)
        <div class="form-group flex mt-5">
            @foreach($options as $name => $fieldData)
                @if ($name == 'looking_for')
                    @foreach ($options[$name]['data'] as $value=>$label)
                        <div class="interestedIn">
                            <input type="checkbox" name="{{ $name.'-'.$value }}" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
                            <label for="{{$name}}-{{ $value }}">{{ $label }}</label>
                        </div>
                    @endforeach
                @endif
            @endforeach
        </div>
    @endisset
    <div class="form-group">
        <label for="" class="textBold">Button</label>
        <input type="submit" class="form-control" name="submit" value="BUTTON">
    </div>
</form>
0 likes
8 replies
Snapey's avatar

whats going off with validation?

You are using a form request but then also have $request->validated()

If you cannot dump the form data, its probably because a validation error occurred

dr24's avatar
Level 2

@snapey

I commented out everything in form request so it doesn't affect anything. I can dump in first foreach but when I enter that foreach for checkboxes then it doesn't work.

dr24's avatar
Level 2

@jlrdw

Yeah I get that, but I would need to change my whole code. My problem is why it doesn't get in foreach

rodrigo.pedra's avatar
Level 56

If you want the checkboxes values as an array the name attribute in all of them should something like name="looking_for[]" so PHP will make them available as an array.

Also the for attribute in the <label> element binds the label to a input by its id attribute. id is the one that should be unique in a HTML document. name tells how to pack the form input fields when submitting

<div class="interestedIn">
  <input type="checkbox" id="{{ $name.'-'.$value }}" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
  <label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>

Note: Just added id and changed name, didn't assessed nor changed your checked logic

1 like
dr24's avatar
Level 2

@rodrigo.pedra

So, I have one small problem now. Like we said this works but now my checkbox values show more options than it should. It duplicates first two values. When I dump $options it shows this.

 array:1 [▼ "looking_for" => array:2 [▼ "data" => array:8
 [▼ 1 => "Zum Verabreden" 2 => "Chatten" 
3 => "Zum Verabreden" 4 => "Chatten" 
5 => "Beziehung" 6 => "Kennenlernen" 
7 => "Sport" 8 => "andere Aktivitäten" ] 
"label" => array:2 [▼ "id" => 2 "label" => "" ] ] ]

And values 1 and 2 are actually Men/Women from select altough it says here Zum Verabreden and Chatten

Can you help I can't seem to find solution on why does this happen?

Please or to participate in this conversation.