The model is a user has many roles and a role has many users
User model
public function roles()
{
return $this->belongsToMany('App\Rol','usuarios_roles','idusuario','idrol');
}
role model
public function usuarios()
{
return $this->belongsToMany('App\User','usuarios_roles','idusuario','idrol');
}
I've seen the documentation but those examples don't work for me. What I need is to restrict a route by role. Example only users with role view can access the route ' users-home '. The create role can access the route users-createNew . Where is this defined? in the routes (I doubt it), in policies creating the file? or in authServicePrivider. I'm very confused
Finally I was able to find the answer. I used middleware. I liked it better and it was easier for me to understand.
Creation of the middleware.
register it in the kernel located at http/kernel. In the routeMiddleware section
Note that role is the alias I am going to use to refer to the middleware.
I apply the filter on the route. File in routes/web.php
Note that only users with role view,insert,admin can see that path. They are separated by semicolons since separated by commas did not work for me.
In the user model I have
// hasRole checks if the user has a specific role in a list of roles or just one. rolesArray .
It can be done in various ways, but I consider that the simplest way is in the Request, which is tied to the respective controller of the route, using the method
authorize()
and relying on the policies.Below I show you (more or less) how this is implemented in a real project in production.
Policy:
Request:
User model:
Here you define the hasRole() method however you want to implement it.
As you can see in the code, in this case there is a Group model, which can work very similar to your Role model.