Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomas95go's avatar

Trying to understand Gates/Policies/Middleware

Hi everyone, What I'm trying to achieve is the following:

I got two type of users for my program, Administrator and Employee, they are related for the following relations:

Two models, no pivot table of:

Role:

public function users()

            {

                return $this->hasMany(User::class);

            }

User:

public function role()

        {

            return $this->belongsTo(Role::class);

        } 

Also I got a CRUD for Products and a CRUD for Users, I want to restrict some actions to the "Employee" so he can not do the CUD actions(Just want to hide the buttons to create, update and delete on the view that shows all the Products) and in the view related to the Users, I do not want that the "Employee" has access to it.

Another thing, I already implement a middleware for non authenticated user's, but this one with roles and permissions is not that easy or I just don't understand it.

So, how can I achieve that with Gates or Policies or even Middleware?

I tried to follow the documentation, but, I don't know what I'm doing for being honest, so I deleted all that I did related to this and I'm asking you guys now.

Note: If you need any peace of code of my program, just ask for it :)!.

  1. Is necessary to have 3 tables to accomplish this?
  2. Is necessary to have a relation between User or Role with Products?
  3. If you share with me some code, please give me some perspective, only if you have time :). 4)So, how can I achieve that with Gates or Policies or even Middleware?

Thanks in advance!

EDIT:

Okay people I just found the solution that I was asking for:

https://laracasts.com/discuss/channels/tips/middleware-to-show-items-based-on-user-roles

So when you try to hidde the buttons or whatever in your view like me, you have to put

            @if (Auth::user()->esAdmin())

            <th><a href="{{('/administrarStock/create')}}"><button type="button" class="btn-primary">Agregar un producto nuevo</button></a></th>

            @endif
0 likes
1 reply
yidekoh556's avatar

The above solution works fine. It check if the user is admin, if yes, it allows. Otherwise, it does not show the buttons.

What if you want to show that button to admin, admin 2, admin 3, admin 4 ... and so on? The code will be messy if you check those all roles in single/multiple if statements. That is why we use Gates and Policies...

As per the documentation, we need to create the policy to the model. and add gate condition to allow the users with certain roles.

Later we use gate::allow method in templates to allow the users. Here, laravel automatically find the roles mentioned in policy (that you have created).

I'm still learning this topic and sorry for this short answer.

Please or to participate in this conversation.