Reputation: 13
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:
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:
array:3 [
"dashboard.view" => "false"
"user.view" => "true"
"user.edit" => "false"
]
Upvotes: 1
Views: 5390
Reputation: 11
Lavel Collective have one intriguing resource that is not documented, as least I never found it in any site. 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. In your specific case, $role->permission should return an model, not array, like normally is in any Laravel app.
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');
}
}
Upvotes: 1
Reputation: 2175
The third parameter is a boolean $checked
, so you may write it like this:
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()
Upvotes: 2