주요기능
// Adding permissions to a user
$user->givePermissionTo('edit articles');
// Adding permissions via a role
$user->assignRole('writer');
$role->givePermissionTo('edit articles');
$user->can('edit articles);
@can('edit articles)
@endcan
사용자 모델에 HasRoles 추가
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
// ...
}
설치
composer require spatie/laravel-permission
// config/app.php
'providers' => [
// ...
Spatie\Permission\PermissionServiceProvider::class,
];
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan config:clear
php artisan migrate
php artisan migrate
Role 과 Permission 만들기
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
// get a list of all permissions directly assigned to the user
$permissionNames = $user->getPermissionNames(); // collection of name strings
$permissions = $user->permissions; // collection of permission objects
// get all permissions for the user, either directly, or from roles, or from both
$permissions = $user->getDirectPermissions();
$permissions = $user->getPermissionsViaRoles();
$permissions = $user->getAllPermissions();
// get the names of the user's roles
$roles = $user->getRoleNames(); // Returns a collection
Artisan Commands
Role 생성하기
php artisan permission:create-role writer
Permission 생성하기
php artisan permission:create-permission "edit articles"
app\Http\Kernel.php
protected $middlewareAliases = [
....
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
]
첫번째 사용자에 admin 권한 부여하기
php artisan make:seeder RolePermissionSeeder
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class RolePermissionSeeder extends Seeder
{
// 초기 퍼미션 세팅
private $permissions = [
'role-list',
'role-create',
'role-edit',
'role-delete',
'permission-list',
'permission-create',
'permission-edit',
'permission-delete'
];
public function run(): void
{
foreach ($this->permissions as $permission) {
Permission::create(['name' => $permission]);
}
//처음 등록되어 있는 사용자를 admin 으로 규정한다.
$user = User::find(1);
if (!$user) {
$user = User::create([
'id' => 1,
'name' => 'admin',
'email' => 'admin@example.com',
'password' => Hash::make('1111'),
]);
}
// admin 그룹을 만든다.
$role = Role::create(['name' => 'Admin']);
$permissions = Permission::pluck('id', 'id')->all();
$role->syncPermissions($permissions);
$user->assignRole([$role->id]);
}
}
사용자에게 권한그룹(Role) 과 퍼미션(Permission)을 부여하는 코드를 작성해 보자.
UserController 생성하기
php artisan make:controller UserController -r
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function index(Request $request)
{
$data = User::latest()->paginate(5);
return view('users.index',compact('data'));
}
public function create()
{
$roles = Role::pluck('name','name')->all();
return view('users.create',compact('roles'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('name','name')->all();
$userRole = $user->roles->pluck('name','name')->all();
return view('users.edit',compact('user','roles','userRole'));
}
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = Arr::except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User updated successfully');
}
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
컨트롤러에서 권한확인 방법
1. role 확인
2. permission 확인
3. role 또는 permission 둘중 어느것이든 가능하게
function __construct()
{
// Admin Rolo 만 가능하게
$this->middleware(['role:Admin']);
// product-create permission 이 있으면, create, store 함수에서만 적용되도록
$this->middleware(['permission:product-create'], ['only' => ['create', 'store']]);
// permission 중복
$this->middleware(['permission:product-list|product-create|product-edit|product-delete'], ['only' => ['index', 'show']]);
$this->middleware(['permission:product-edit'], ['only' => ['edit', 'update']]);
$this->middleware(['permission:product-delete'], ['only' => ['destroy']]);
// Role 또는 Permission 아무거나
$this->middleware('role_or_permission:Admin|product-create', ['only' => ['create', 'store']]);
}
route 에서도 동일하게 적용하면 된다.
'Laravel' 카테고리의 다른 글
Laravel - Metronic 8 / 관리자 페이지 (1) | 2024.05.05 |
---|---|
Laravel - 기존사이트에 spatie/laravel-permission 적용순서 (0) | 2024.05.05 |
Laravel - RouteServiceProvider 에 대해서 (여러개의 라우팅 파일작성하기) (0) | 2024.03.04 |
Laravel - Factory, Seeder (테스트 User 생성하기) (0) | 2024.02.12 |
Laravel - Resource 컨트롤러에 대해서 (0) | 2024.01.31 |