简体   繁体   English

Laravel表单集体复选框

[英]Laravel form collective checkbox

so how can I make a default checked/unchecked checkbox, with values from the data base? 因此,如何使用数据库中的值制作默认的选中/未选中复选框? I'm using Form model from laravel collective and my checkbox field is this: 我正在使用Laravel Collective的Form模型,而我的复选框字段是这样的:

Form::model($role, ['route' => ['the_route', $role->slug], 'method' => 'patch'])

    @foreach ($permissions as $permission)
        Form::checkbox('permission['.$permission->slug.']', 'true', null, ['class' => 'square'])
    @endforeach

Form::close()

The thing is that $role->permissions returns an array like this: 问题是$role->permissions返回如下数组:

array:3 [
  "dashboard.view" => "false"
  "user.view" => "true"
  "user.edit" => "false"
]

The third parameter is a boolean $checked , so you may write it like this: 第三个参数是布尔值$checked ,因此您可以这样编写:

Form::model($role, ['route' => ['the_route', $role->slug], 'method' => 'patch'])

    @foreach ($permissions as $slug => $value)
        Form::checkbox('permission['.$slug.']', 'true', (bool) $value, ['class' => 'square'])
    @endforeach

Form::close()

Lavel Collective have one intriguing resource that is not documented, as least I never found it in any site. Lavel Collective有一个没有记录的有趣资源,至少我从未在任何站点中找到它。 Name your checkbox with them same name that you gave for relation between your two models, like "permissions", and then Laravel Collective will check all input that are in that relation. 使用与您在两个模型之间的关系所给的名称相同的名称来命名您的复选框,例如“权限”,然后Laravel Collective将检查该关系中的所有输入。 In your specific case, $role->permission should return an model, not array, like normally is in any Laravel app. 在您的特定情况下,$ role-> permission应该返回一个模型,而不是数组,就像通常在任何Laravel应用程序中一样。

Check an sample code: 检查示例代码:

{!! Form::model($role, ['route' => ['roles.update',  $user->id], 'method' => 'put']) !!}

    <div class="row form-group">

        @foreach($permissions as $permission)
            <div class="col-sm-3">
                {!! Form::checkbox('permissions[]', $permission->id) !!}
                {!! Form::label('permissions', $permission->name) !!}
            </div>
        @endforeach

    </div>

{!! Form::close() !!}

// Role model // 榜样

class Role extends Model 
{

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'permission_role');
    }
}

// Permission model //权限模型

class Permission extends Model
{

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'permission_role');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM