composer require epartment/nova-dependency-container
app/Models/Role.php
// ...
public function permissions()
{
return $this->belongsToMany(Permission::class, 'permission_role');
}
// ...
app/Nova/Role.php
// ...
use Epartment\NovaDependencyContainer\HasDependencies;
use Laravel\Nova\Fields\Boolean;
// ...
public function fields(NovaRequest $request)
{
$permissions = \App\Models\Permission::all()->pluck('name', 'id')->toArray();
$booleanFields = collect($permissions)->map(function ($permissionName, $permissionId) {
return Boolean::make($permissionName, 'permission_'.$permissionId)
->resolveUsing(function () use ($permissionId) {
if ($this->resource) {
$this->resource->load('permissions');
return $this->resource->permissions->contains($permissionId);
}
return false;
})
->fillUsing(function ($request, $model, $attribute, $requestAttribute) use ($permissionId) {
$model->save();
$hasPermission = $model->permissions->contains($permissionId);
if ($request[$requestAttribute] && !$hasPermission) {
$model->permissions()->attach($permissionId);
} elseif (!$request[$requestAttribute] && $hasPermission) {
$model->permissions()->detach($permissionId);
}
});
})->toArray();
return array_merge([
ID::make()->sortable(),
Text::make('Name')
->sortable()
->rules('required', 'max:255'),
], $booleanFields, [
BelongsToMany::make('Permission', 'permission', Permission::class),
]);
}