1

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>

code for $options variable

public static function getProfileLookingForDisplayOptions()
{
    $options = [
        'gender' => ['id' => 1, 'label' => "Interessiert an"],
        'looking_for' => ['id' => 2, 'label' => ""]
    ];

    $data_options = [];
    foreach ($options as $field => $value) {
        $data_options[$field]['data'] = Value::fieldValues($field);
        $data_options[$field]['label'] = $options[$field];

        if (!in_array($field, ['gender', 'looking_for'])) {
            $data_options[$field]['data'][100] = "Doesn't matter";

        }
    }
    //dd($data_options);
    return $data_options;
}
1
  • This isn't the right function, the options are being returned by Value::fieldValues($field), the error is there. Is Value a model? Check if it is filtering the options correctly, this seems to be the problem. Commented May 4, 2020 at 23:28

1 Answer 1

1

If I understand your problem correctly, to deal with multiple checkboxes on PHP you need to add [] to its name property. That way, PHP knows it should interpret theses values as an array.

Also, your input name is not matching with $data[$fieldName].

Do it like this:

    @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 }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }} id="{{$name}}-{{ $value }}">
                            <label for="{{$name}}-{{ $value }}">{{ $label }}</label>
                        </div>
                    @endforeach
                @endif
            @endforeach
        </div>
    @endisset
Sign up to request clarification or add additional context in comments.

6 Comments

I put [] but it is still the same, nothing changes. Any more ideas?
You should also consider using the Form class, I wrote an article about this. Read it here: guscosta.com.br/post/3
Yeah now it succesfully updates the database. But now I have one more problem. 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
There is some problem on the controller that loads these options, can you share that code?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.