如何在路由的 laravel 中间件中添加 OR 关系

How can I add OR relationship in laravel middleware for a Route

我正在使用 spatie/laravel-permission 为我的路线添加权限。

我有一个路由可以通过两个权限访问(earningsfinancial_fund)。用户不需要同时拥有访问控制器的权限。他可以通过拥有其中一种或两种权限来访问控制器。

我试过写这样的东西。

Route::group(['middleware' => ['can:earnings']], function () {
    Route::get('/payment', [PaymentsController::class, 'getAll']);
    Route::post('/payment/cash', [PaymentsController::class, 'addCashPayment']);
});
Route::group(['middleware' => ['can:financial_fund']], function () {
    Route::get('/payment', [PaymentsController::class, 'getAll']);
    Route::post('/payment/cash', [PaymentsController::class, 'addCashPayment']);
});

但是上面的代码只允许具有can:earnings权限的用户访问路由,它不允许具有can:financial_fund权限的用户。

我也试过这样写

Route::group(['middleware' => ['can:earnings,financial_fund']], function () {
    Route::get('/payment', [PaymentsController::class, 'getAll']);
    Route::post('/payment/cash', [PaymentsController::class, 'addCashPayment']);
});

但这需要当前用户拥有这两个权限。

我怎么知道我只希望至少存在一个权限?

我发现 Laravel 引入了 canAny 用于 blade 模板。有什么方法可以在我的 api.php 文件中定义路由时使用它?

我通过创建一个新的中间件修复了它

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AuthorizeCanAny
{
    public function handle(Request $request, Closure $next, ...$permissions)
    {
        if (!$request->user()) {
            abort(403);
        }

        $userPermissions = array_map(function ($e) {
            return $e['name'];
        }, $request->user()->permissions->toArray());

        $userPermissionsIntersect = array_intersect($userPermissions, $permissions);

        if (!sizeof($userPermissionsIntersect)) {
            abort(403);
        }

        return $next($request);
    }
}

将中间件添加到 kernal.php 文件

protected $routeMiddleware = [
    ...,
    'canAny' => AuthorizeCanAny::class,
];

然后在路由器中使用

Route::group(['middleware' => ['canAny:earnings,financial_fund']], function () {
    Route::get('/payment', [PaymentsController::class, 'getAll']);
    Route::post('/payment/cash', [PaymentsController::class, 'addCashPayment']);
});