PHP code example of jundayw / laravel-policy

1. Go to this page and download the library: Download jundayw/laravel-policy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jundayw / laravel-policy example snippets



namespace App\Models;

use Jundayw\LaravelPolicy\PolicyContract;
use Jundayw\LaravelPolicy\Policy;

class Manager extends Authenticate implements PolicyContract
{
    use Policy;

    /**
     * @param string $ability
     * @param mixed $arguments
     * @return string[]
     */
    public function getPolicies(string $ability, mixed $arguments): array
    {
        // do anything for get polices
        return [
            // "backend.module.list",
            // "backend.module.create",
            // "backend.module.store",
            // "backend.module.edit",
            // "backend.module.update",
            // "backend.module.destroy",
            // "backend.policy.list",
            // "backend.policy.create",
            // "backend.policy.store",
            // "backend.policy.edit",
            // "backend.policy.update",
            // "backend.policy.destroy",
            // "backend.role.*",
            // "backend.*.*",
        ];
    }
}

class AuthController extends CommonController
{
    public function __construct()
    {
        $this->middleware('policy');
    }
}

Route::middleware('policy')->group(function(){});

use Jundayw\LaravelPolicy\Policies\Policy;
/**
 * Handle an incoming request.
 *
 * @param Request $request
 * @param Closure $next
 * @return Response|PolicyException
 */
public function handle(Request $request, Closure $next)
{
    // 传入当前请求需要的权限标识符,可自定义任意形式
    // 如
    // admin.role.delete
    // admin/role/delete
    // admin-role-delete
    // adminRoleDelete
    // ...
    // 注意与 getPolicies 方法返回类型一致
    $policy = '';
    if ($request->user()->can($policy, [Policy::class])) {
        return $next($request);
    }
    // 自定义无权访问行为
    throw new Exception('UnAuthorized Access.');
}

php artisan vendor:publish --tag=artisan-policy-config

POLICY_ENABLED=false