YVS1102
YVS1102

Reputation: 2740

Laravel menu based on role?

i have codeigniter background. Now, i'm learning about laravel. So, i'm in this condition (Example), I'm trying to create a webapp, which has multiple users. The UsersType A , they can access menu a, menu b & menu c and UsersType B they only can access Menu a.

Now, i'm using https://github.com/lavary/laravel-menu . Well, if it's only have two types , i can write it manually. But, what if there are five types of user or more.

When i'm using codeigniter. I create 4 table Users , UsersType , Menu & MenuAccess. You must be understand how it's work. I just, play it with query then i show it.

UsersType (Users) -> TypeId (UsersType) -> MenuId (MenuAccess) -> MenuId (Menu)

I already use google and I found this https://github.com/Zizaco/entrust but what i can see from that package. It's only give the permission on the action (input,edit & delete)

So, Can i do my codeigniter way in my laravel ? Save my routes properties than show it in my rouotes/web.php (I don't know if it possible, haven't try it yet). sorry for my english.

Upvotes: 4

Views: 10851

Answers (2)

Matthew Daly
Matthew Daly

Reputation: 9476

As mentioned in the comments,it sounds like what you want is the ability to conditionally display content based on whether a user has certain permissions.

There's a number of implementations of this. Essentially what they all do is store permissions that can be granted to users, and optionally store roles that allow permissions to be assigned to a role and then users can be given that role, automatically granting them the permissions associated with that role.

I've found spatie/laravel-permission which appears to be quite good. Then, if you pass your user model into the view, you can do something like this:

@if ($user->can('edit-posts'))
<a>Edit post</a>
@endif

That should be flexible enough that it can be reused for different permissions too. If that doesn't do the trick, then it's not hard to roll your own permission system using Laravel's authorization system and you should be able to use the can() method in the same way.

Upvotes: 3

Nathan Heffley
Nathan Heffley

Reputation: 610

What I would do is put a function in the User class which checks it's own permission and then returns a view which contains the menu that user has access to.

public function menu()
{
    switch($this->role) {
        case 'admin':
            return view('menus.admin');
        [etc]
    }
}

Then in the view just check if the user is logged in and show the menu:

@if Auth::check()
    {{ Auth::user->menu() }}
@endif

Upvotes: 5

Related Questions