GATES de laravel. Restrict routes by role

-1

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 have seen the documentation but those examples do not work for me. What I need is to restrict a route by role. Example only users with see role can access the path ' users-start '. The create role can access the path users-createNew . This where is it defined? in the routes (I doubt it), in policies creating the file? or in authServicePrivider. I'm very confused

    
asked by santiago 10.06.2017 в 04:44
source

1 answer

1

Finally I could find the answer. I used middleware. I liked it more and it was easier to understand for me.

Creation of the middleware.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    public function handle($request, Closure $next, $role)
    {

        if (auth()->check() && auth()->user()->hasRole($role)) {
            return $next($request);
        }

        return redirect('/');
    }
}

register it in the kernel located in http / kernel. In the routeMiddleware section

'role' => \App\Http\Middleware\CheckRole::class,

Note that role is the alias I am going to use to refer to the middleware.

I apply the filter in the route. File in routes / web.php

Route::get('usuarios', 'UsuarioController@index')->middleware('role:ver;insertar;admin');

Note that only users with a view, insert, admin role can see that route. They are separated by semicolons since separated by commas did not work for me.

In the user model I have

    public function roles()
    {
        return $this->belongsToMany('App\Rol','usuarios_roles','idusuario','idrol');
    }

// hasRole verifies if the user has a specific role in a list of roles or only one. rolesArray.

        public function hasRole(string $roleSlug)
        {


             $roles = $roleSlug;
             $rolesArray = explode(';',$roles);  
             $roles = $this->roles()->whereIn('nombre', $rolesArray)->count() > 0;
             return $roles;

        }
    
answered by 11.06.2017 / 00:57
source