I have role &permission as below designed table.
role table
user_id | role_id
1 | 1
1 | 2
role module table
role_id | module_id
1 | 1
1 | 2
module task table
module_id taks_id
1 | 1
1 | 2
task permission table
task_id permission
1 | [true,true,true,false]
1 | [true,false,false,false]
I have relation between role_module and module_taks as below
class Role extends Model
{
use HasFactory;
public function modules()
{
return $this->belongsToMany(Module::class, 'role_modules');
}
}
module task
class Module extends Model
{
use HasFactory;
public function tasks()
{
return $this->belongsToMany(Task::class, 'module_tasks');
}
}
But I need something like each user has own roles, modules, tasks and task permission. Any advice or guidance for database design or relation design would be greatly appreciated, Thanks.
CodePudding user response:
If I understand this correctly you in addition to the above, need it to be possible to give specific users roles, modules, tasks, and task permissions.
There are several ways of approaching this, and I am pretty sure there are packages out there that can help you set this up rather quickly. But if you want to develop it in-house then I would suggest something like below using MorphPivot.
user table
id | name
1 | John
2 | Jane
role table
id | name
1 | user
2 | admin
permission table
id | name
1 | ReadOnly
2 | Manage
permissionable morph pivot table
permission_id | permissionable_id | permissionable_type
1 | 1 | App\Models\Role
1 | 1 | App\Models\Role
2 | 2 | App\Models\Role
2 | 1 | App\Models\User
Then you can do the same thing with modules and tasks. This will allow you to assign any permission to any type of model, which makes your database much nicer, and decreases development time by a lot when you add new things in the future.
use Illuminate\Database\Eloquent\Relations\MorphPivot;
class Permissionable Pivot extends MorphPivot
{
protected $table = 'permissionable';
public $incrementing = true;
}
class Role extends Model
{
use HasFactory;
public function permissions()
{
return $this->morphToMany('App\Models\Permission', 'permissionable')
->using(Permissionable Pivot::class);
}
}