Laravel crear roles para usuarios

Laravel crear roles para usuarios

Requisito

php artisan make:auth

Crear el modelo del Role y la migración

php artisan make:model Role -m

Editamos el archivo de migración para role

public function up(){  
  Schema::create('roles', function (Blueprint $table) {    
    $table->increments('id');    
    $table->string('name');    
    $table->string('description');    
    $table->timestamps();  
  });
}
public function down(){  
  Schema::dropIfExists('roles');
}

Crear tabla usuario vs rol

php artisan make:migration crear_tabla_usuario_rol_tabla

Editar el archivo de migración

public function up(){  
Schema::create('role_user', function (Blueprint $table) {    
$table->increments('id');    
$table->integer('role_id')->unsigned();    
$table->integer('user_id')->unsigned();  
});
}

public function down(){  
Schema::dropIfExists('role_user');
}
public function up(){  
  Schema::create('role_user', function (Blueprint $table) 
  {    
    $table->increments('id');    
    $table->integer('role_id')->unsigned();    
    $table->integer('user_id')->unsigned();  
  });
}
public function down(){  
  Schema::dropIfExists('role_user');
}

Agregar en el modelo User.php la función roles

public function roles() {   return $this->belongsToMany(Role::class); }

Agregar en el modelo Role.php la función users

public function users() {   return $this->belongsToMany(User::class); }

Agregar los Seeder para usuarios y roles (cargar datos predeterminados)

php artisan make:seeder RoleTableSeeder php artisan make:seeder UserTableSeeder

En el directorio database/seeds/

Editar el archivo RoleTableSeeder.php

use Illuminate\Database\Seeder;
use App\Role;
use Illuminate\Database\Seeder;

class RoleTableSeeder extends Seeder{    
public function run()    {        
$role_employee = new Role();        
$role_employee->name = 'employee';        
$role_employee->description = 'A Employee User';        
$role_employee->save();        
$role_manager = new Role();        
$role_manager->name = 'manager';        
$role_manager->description = 'A Manager User';        
$role_manager->save();    
}
}

Editar el archivo UserTableSeeder.php

use Illuminate\Database\Seeder;
use App\Role;
use App\User;
use Illuminate\Database\Seeder;

class UserTableSeeder extends Seeder{    
public function run()    {        
$role_employee = Role::where('name', 'employee')->first();        $role_manager = Role::where('name', 'manager')->first();        
$employee = new User();        

$employee->name = 'Employee Name';        
$employee->email = 'employee@example.com';        
$employee->password = bcrypt('secret');        
$employee->save();

$employee->roles()->attach($role_employee);        
$manager = new User();        
$manager->name = 'Manager Name';        
$manager->email = 'manager@example.com';        
$manager->password = bcrypt('secret');        
$manager->save();        
$manager->roles()->attach($role_manager);    
}
}

Editar el archivo DatabaseSeeder.php

public function run() {   $this->call(RoleTableSeeder::class);   $this->call(UserTableSeeder::class); }

Editar el modelo de usuarios User.php

public function authorizeRoles($roles){  
if (is_array($roles)) {      
return $this->hasAnyRole($roles) ||              abort(401, 'This action is unauthorized.');  
}  
return $this->hasRole($roles) ||          abort(401, 'This action is unauthorized.');
}

public function hasAnyRole($roles){  
return null !== $this->roles()->whereIn(‘name’, $roles)->first();
}

public function hasRole($role){  
return null !== $this->roles()->where(‘name’, $role)->first();

}

Registrar usuarios con rol predeterminado «employee» /Http/Controllers/Auth/RegisterController.php

use App\Role;
class RegisterController extends Controller{
protected function create(array $data){    
$user = User::create([
'name'=> $data['name'],
'email'=> $data['email'],
'password' => bcrypt($data['password']),
]);    
$user->roles()->attach(Role::where('name', 'employee')->first());
return $user;
}
}

Ejecutar los archivos Seeder

php artisan migrate:fresh --seed

Un ejemplo de como utilizar en los controladores

class HomeController extends Controller{  
public function __construct()  {    
$this->middleware('auth');  
}  
public function index(Request $request)  {    
$request->user()->authorizeRoles(['employee', 'manager']);    
return view('home');  
}

Añadir al Middleware

Creamos la verificación del rol

php artisan make:middleware CheckRole

Editamos el archivo CheckRole.php

public function handle($request, Closure $next, $role){    
if (! $request->user()->hasRole($role)) {
return redirect('home');
return $next($request);
}

Registramos el Middleware en la ruta app/Http/Kernel.php

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

Agregamos en las rutas.

Route::put('post/{id}', function ($id) {     //escribir validacones })->middleware('auth', 'role:admin');

¿Cómo validamos multiples usuarios con Middleware?

En las rutas agregamos los usuarios con la separación de «|»

Route::group(['middleware' => ['auth', 'role:employee|manager']], function () {   Route::get('/admin/home', 'AdminController@index')->name('home'); }); 

Modificaremos el Middleware CheckRole.php

<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class CheckRole{       
public function handle($request, Closure $next, $roles){                
if ( !Auth::user()->hasRoles($roles) ) {            
return redirect('/404');        
}        
return $next($request);    
}
}

Editar el modelo User.php

public function hasRoles($roles){
$roles_array = explode("|", $roles);
if ($this->roles()->whereIn('name', $roles_array)->first()) {
return true;
}
return false;
}

Deja un comentario

dieciseis + 17 =

Cerrar menú