Phân quyền với laravel permission
Cài đặt laravel app với lệnh
"composer create-project laravel/laravel la11permission"
Tiếp theo cài đặt gói :
" composer require spatie/laravel-permission "
Tiếp theo public các config với lệnh :
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
Chúng ta cần thực hiện theo các bước cơ bản sau là được :
https://spatie.be/docs/laravel-permission/v6/installation-laravel
Và mình thêm trait HasRole vào trong model nào mình cần sử dụng để lấy info người đăng nhập :
" use HasRoles;"
Chúng ta cần thêm middleware để có thể sử dụng bận sau : bootstrap\app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
Sử dụng trong middleware \routes\web.php:
Route::get('post', [PostController::class, 'index'])
    ->middleware(['role_or_permission:admin|post.view']);
Ở đây mình sử dụng middleware còn nếu sử dụng trong controller chúng ta đã tách biệt ra 1 function là middleware :
Ví dụ :
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
// class PostController extends Controller implements HasMiddleware
class PostController extends Controller
{
    public static function middleware(): array
    {
    return [
        'auth',
        new Middleware('permission:post.index', only: ['index']),
        new Middleware('subscribed', except: ['store']),
    ];
    }
    public function demo()
    {
        Gate::authorize('viewAny', Post::class);
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Gate::authorize('viewAny', Post::class);
        //  dd($user);
        return view('post.index');
    }
    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        Gate::authorize('create', Post::class);
        dd(3);
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }
    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
Trong policy thì chúng ta có 1 file Policy sử dụng như sau :
<?php
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Carbon;
class PostPolicy
{
    // chạy trước khi vào policy có tác dụng đảm bảo người có quyền admin có thể vượt qua mọi thứ
    public function before(?User $user)
    {
        if ($user->hasRole('admin')) {
            return true;
        }
        return null;
    }
    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(?User $user): bool
    {
        return true;
    }
    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Post $post): bool {}
    /**
     * Determine whether the user can create models.
     */
    public function create(User $user): bool
    {
        if ($user->id === 1) {
            return true;
        } else {
            return true;
        }
    }
    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Post $post): bool
    {
        if ($post->created_at > Carbon::now()->subHours(2)) {
        }
        return $user->id === $post->user_id || $user->id === $post->user_id;
    }
    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, Post $post): bool
    {
        //
    }
    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, Post $post): bool
    {
        //
    }
    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, Post $post): bool
    {
        //
    }
}
Trong view thì ta sử dụng như sau :
@extends('layouts.app')
@section('content')
@can('post.create') // dùng cho laravel perrmission ,
<a name="" id="" class="btn btn-primary" href="#" role="button">Create permission</a>
@endcan
@can('viewAny',App\Models\Post::class) // dùng cho policy
<a name="" id="" class="btn btn-primary" href="#" role="button">Create</a>
@endcan
<h3>Xin chào</h3>
@endsection
Đây là ví dụ về cách sử dụng permission kết hợp policy trong middleware ,controller và view
 
                                    
                 
                 
                 
                