简体   繁体   中英

Laravel permissions pivot table

I am making custom permissions ,

I would like them to be divided into sections eg orders, customers etc. and each section would have some permission eg edit, delete, add. Just to check if a particular user has access I would have to start with the Section model?

Because I can't do something like Auth::user()->permissions()->with('sections')->contains('name','display')->contains('sections','order')

I would like to simply check if the user has access to, for example, order.display . I have a feeling that this section does not make sense here.

How to do it? I know there is a spatie(laravel-permission), but there is a role division there.

Example schema of the database (user_permission is a pivot): 在此处输入图像描述

My advice is if you're looking for something simple, drop the sections table and just have all permissions in the permissions table. Say you had a section called dashboard in permissions you could have view_dashboard edit_dashboard etc. Then to check the user is authorised, implement the hasManyThrough logic below Official documentation

(untested)

public function permissions()
{
    return $this->hasManyThrough(Permissions::class, UserPermissions::class);
}

public function permission_check($permission_to_check)
{
    return $this->permissions->contains($permission_to_check);
}

You could then eager load permissions() on the user model to reduce DB queries if you are checking permission in many places.

Hope this helps, let me know if I can assist further:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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