那么如何使用数据库中的值创建默认的选中/取消选中复选框?我使用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()
问题是$role->permissions
返回一个这样的数组:
array:3 [
"dashboard.view" => "false"
"user.view" => "true"
"user.edit" => "false"
]
答案 0 :(得分:1)
第三个参数是一个布尔$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()
答案 1 :(得分:1)
Lavel Collective有一个有趣的资源没有记录,至少我从来没有在任何网站上找到它。将您的复选框命名为您为两个模型之间的关系命名的相同名称,例如" permissions",然后Laravel Collective将检查该关系中的所有输入。在您的特定情况下,$ role->权限应该返回一个模型,而不是像任何Laravel应用程序中一样的数组。
检查示例代码:
{!! 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() !!}
//角色模型
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany(Permission::class, 'permission_role');
}
}
//权限模型
class Permission extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class, 'permission_role');
}
}