仅保存1个单选按钮,而不是2个

时间:2019-03-14 09:07:04

标签: laravel laravel-5

在我的页面中,我可以有多个addresses,但是user只能选择一个address

我遇到的问题是两个单选按钮都被保存了,而不仅仅是一个。

因此,如果用户有2个addresses,则只有一个应拥有selected = 1,而另一个地址应为selected = 0,但目前两者都是address = 1

我只能选择1个address并保存到数据库中。我知道我正在传递所选单选按钮的ID,但我希望能做到这一点。

E.G:当用户保存其第一个地址,然后将其另存为所选地址(selected = 1)时,他们添加的所有其他地址将为(selected = 0)

如果他们改变主意并希望将其第二个地址用作其使用的地址,则选择它,然后地址将变成这样,地址1 (selected = 0)和地址2将变为(selected = 1)。 / p>

我希望这是有道理的。如果没有,请告诉我。

我的表格

@foreach($addresses as $address)
    <div class="col-lg-4">
        <form id="address-radio" action="{{ route('account.post.addresses.radio', $address->id) }}" method="post">
            @csrf
            <div class="form-check">
                <input type="radio" class="form-check-input" name="address_option" id="address_{{ $address->id }}" {!! $address->selected == '1' ? 'checked' : '' !!}>
                <label for="address_{{ $address->id }}" class="form-check->label">
                    @if(!empty($address->complex))
                        {{ $address->complex }} <br>
                    @endif
                    {{ $address->address }} <br>
                    {{ $address->suburb }} <br>
                    {{ $address->city }} <br>
                    {{ $address->province }} <br>
                    {{ $address->postal_code }} <br>
                </label>
            </div>
        </form>
    </div>
@endforeach

<script>
    $(document).ready(function(){
        $('input[type="radio"]').on('change', function(){
            $(this).closest("form").submit();
        })
    })
</script>

这是我的功能

public function postAddressesRadio(Request $request, $id)
{
    $selected = Address::findOrFail($id);
    $user_id = Auth::user()->id;

    $not_selected = $selected->where('id', '!=', $id)
                                ->where('user_id', $user_id)->get();

    foreach($not_selected as $selected)
    {
        $selected->selected = "0";
    }

    if($request->address_option == 'on'){
        $selected->selected = '1';
    }

    $selected->save();

    return redirect()->back()->with('success', 'Address was updated');
}

1 个答案:

答案 0 :(得分:0)

所以我设法做到了。我不确定是否有更好的方法,但这行得通。

在我的工作中,我做了

public function postAddressesRadio(Request $request, $id)
{
    $address = Address::findOrFail($id);
    $user_id = Auth::user()->id;

    $addresses = Address::where('user_id', $user_id)->get();

    foreach($addresses as $address)
    {
        if($address->id == $id)
        {
            $address->selected = "1";
        }else{
            $address->selected = "0";
        }

        $address->save();
    }