从复选框获取数据到 Laravel 控制器

时间:2021-02-11 19:23:55

标签: php laravel forms laravel-5 laravel-8

这看起来很简单。但有没有被我难倒... 我有一个包含一些记录的表格,一个单元格中有一个引导程序自定义开关输入。 开关渲染正确。但我无法将数组放回控制器中。

刀片视图

+

控制器

<form action="{{ route('Admin.Livestatus.Update', $prop, ['prop' => $prop->id]) }}" method="POST">
    @csrf
    @method('PUT')
    <div class="custom-control custom-switch">
        <input  type="checkbox" 
                class="custom-control-input" 
                id="sitelive" 
                name="sitelive[]" 
                value="{{ $prop->sitelive }}" 
                onchange="javascript:this.form.submit()" 
                @if($prop->sitelive == 1) checked @endif>
        <label class="custom-control-label" for="sitelive"></label>
    </div>
</form>

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

看看这个例子,这可能会有所帮助 enter image description here

这是我在测试时的一个项目中的一个,在此列客户端需要一一更新每个用户的状态(活动/非活动)。

这是html部分

'<div class="custom-control custom-switch custom-control-success custom-control-lg mb-2">
  <input type="checkbox" class="custom-control-input isUserActive" data-url="'.route('admin.users.updateUserStatus').'" data-user-id="'.$user->id.'" id="example-sw-custom-success-'.$user->id.'" name="is_active[]" value="'.$user->is_active.'" '.($user->is_active === 'active' ? 'checked="checked"' : ' ').'>
  <label class="custom-control-label" for="example-sw-custom-success-'.$user->id.'"></label>
</div>'

这是在完全加载数据表后呈现的字符串,我在 Laravel 中使用此包用于数据表来呈现数据表。

"yajra/laravel-datatables": "^1.5"

关于处理 bootstrap-switch Laravel 控制器

   /**
     * Update User Status
     * @param Request $request
     * @return JsonResponse
     */
    public function updateUserStatus(Request $request){
        try{
            User::where('id',$request->get('user_id'))->update([
               'is_active'  => $request->get('status')
            ]);
            if($request->get('status') === 'active'){
                $getUserData = User::where('id',$request->get('user_id'))->first();
                Mail::to($getUserData)->send(new UserActiveRegistration($getUserData));
            }
            return response()->json([
                'status'    => 'success',
                'message'   => 'User Status Updated successfully.'
            ]);
        }catch (Exception $exception){
            return response()->json([
                'status'    => 'error',
                'message'   => $exception->getMessage()
            ]);
        }
    }

Jquery 部分

/*
* User Status Update
*/
if($('.isUserActive').val() === 'active'){
    $('.isUserActive').attr('checked','checked').toggle("click");
}else{
    $('.isUserActive').removeAttr('checked');
}
$(document).on('change','.isUserActive',function () {
    if($(this).val() === 'active'){
        $(this).val('inactive');
    }else{
        $(this).val('active');
    }
    Swal.fire({
        title: 'Are you sure?',
        text: "You want to update the status of the user ?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, update it!'
    }).then((result) => {
        if (result.value) {
            let table = $('#dataTables').DataTable();
            $.ajax({
                type: 'POST',
                url: $(this).attr('data-url'),
                data: {
                    user_id     : $(this).attr('data-user-id'),
                    status      : $(this).val(),
                },
                dataType: 'json',
                success: function(data) {
                    Swal.fire(
                        'Updated!',
                        '',
                        'success'
                    )
                    table.ajax.reload();
                },
                error: function(data) {
                    console.log(data);
                }
            });
        }
    });
});

这只是在表中处理 bootstrap-switch 的另一种方式。

我希望这会有所帮助。

答案 1 :(得分:0)

感谢您的回答.... 我刚刚弄清楚我做错了什么,这是不了解复选框如何工作的组合(空时不返回数据)。该值是选中框时发送的值,也是我对链接标签和表单元素的理解。也不必要地在控制器中进行了验证(这会失败)......基本上一切!

仍然希望这可以帮助处于类似情况的人

刀片

<form action="{{ route('Admin.Livestatus.Update', $prop, ['prop' => $prop->id]) }}" method="POST">
    @csrf
    @method('PUT')

    <div class="custom-control custom-switch">
        <input type="checkbox" 
               name="sitelive" 
               class="custom-control-input" 
               onchange="javascript:this.form.submit()" 
               id="{{$prop->id}}" 
               value="1" 
               @if($prop->sitelive === 1) checked @endif>
        <label class="custom-control-label" for="{{$prop->id}}"></label>
    </div>
</form>

控制器

public function update(Request $request, $id)
{
    $prop = Properties::findorFail($id);
    $prop->sitelive = $request->sitelive;    
    $prop->save();

    return redirect()->route('Admin.Admin',  [ 'Property', 'All' ]);
}

所以基本上,如果选择了切换。然后将 DB 记录设置为 1。否则将其设置为 null,因为没有返回任何内容..