dr24
3 months ago
355
8
Laravel

Problem with storing checkbox values in database

Posted 3 months ago by dr24

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', '[email protected]')->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>

Please sign in or create an account to participate in this conversation.