php - Laravel 表单复选框数据

标签 php database laravel

我有两张 table ;两者都有几列。一个是我拥有用户可以选择的所有许可证(带有复选框),另一个是我存储用户拥有的许可证。

我创建了一个模型来获取所有许可,并创建了一个模型来获取用户拥有的许可。

现在,我不明白如何创建所有许可证的 View ,其中用户已经拥有的许可证已经被选中 - 例如,当我使用这些复选框创建表单时,我如何检查用户是否已经拥有许可证.

我可以获取值,但无法使用 @if 语法。

这是我目前的代码:

<div class="form-group col-sm-12">
    <div class="form-check form-check-inline">
        @foreach($all_license as $all_licen_row)
            @foreach($drive_licenses as $lisen)
                @if($lisen->license_id==$all_licen_row->id)

                    <input class="form-check-input" type="checkbox"
                           name="{{$all_licen_row->license_id}}" checked>

                    <label class="form-check-label"
                           for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)

                @else
                    <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}">

                    <label class="form-check-label"
                           for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)
                @endif
            @endforeach
            @if($errors->has('id'))
                <span class="help-block">
                <strong class="text-danger">{{ $errors->first('drive_licence') }}</strong>

            </span>
            @endif
        @endforeach

    </div>
</div>

最佳答案

像这样的事情通常在不使用内部循环的情况下更容易处理。您可以通过将 drive_licenses 中的 id 存储到数组中并简单地检查 $all_license 来检查在遍历 $all_license 之前应该选择哪个 id > id 存在于数组中。示例:

<?php 
    $ids = array();
    foreach($drive_licenses as $lisen) {
        array_push($ids, $lisen->license_id)
    }
?>
@foreach($all_license as $all_licen_row)
    @if(in_array($all_licen_row->id, $ids))

        <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}" checked>
        <label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>

    @else
        ...
    @endif
@endforeach

如果需要,您还可以使用三元运算符(例如,(?:))来缩短您的代码。示例:

@foreach($all_license as $all_licen_row)

    <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}"{{ (in_array($all_licen_row->id, $ids) ? ' checked' : '') }}>
    <label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>

@endforeach

关于php - Laravel 表单复选框数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52860814/

相关文章:

php - 如何使用 CodeIgniter 3.1.0 将 Facebook 用户基本信息保存到数据库

json - 从 PostgreSQL 中的函数返回中删除双引号

python - 在 Python 中使用 SQLite3 选择多个列

php - 我在我的文件夹中找不到 bootstrap.css

php - 如何在 laravel 5 中模拟模型上的 create 方法?

javascript - Webix 数据表 ||加载数据服务器端

java - Android:用户使用 php 登录时出错

sql - 在 PL/SQL 中创建登录过程

Laravel 验证 : required field in not required array

mysql - 由于外键失败,无法使用迁移在 Laravel 5.5 中创建表