如何在 Laravel 中为多模型路由命名策略?

How to name a policy for multimodel route in Laravel?

我正在尝试为此路由编写策略:

Route::delete(
    'users/{user}/locations/{location}',
    [UserLocationController::class, 'destroy'],
)->middleware('can:delete,user,location');

但我不知道如何命名策略以允许 Laravel 自动找到它。我正在从 location_user table 中删除记录,但我没有此 table 的模型。我的策略函数如下所示:

public function delete(User $user, User $userModel, Location $location)
{
    return $user->id === $userModel->id
        && $user->locations->contains($location->id);
}

我尝试过 LocationUserPolicyUserLocationPolicyLocationPolicy 等名称,但其中 none 行得通。您对如何命名策略或如何编写自定义逻辑以允许 Laravel 找到它有什么建议吗?

好的,我在 Laravel 文档中找到了正确的答案 :D 诀窍在于更改 can 中间件属性的顺序。

The first element in the array will be used to determine which policy should be invoked, while the rest of the array elements are passed as parameters to the policy method and can be used for additional context when making authorization decisions.

所以我改变了路线:

Route::delete(
    'users/{user}/locations/{location}',
    [UserLocationController::class, 'destroy']
)->middleware('can:delete,location,user');

将策略命名为 LocationPolicy(按第一个属性)并将我的策略函数更改为:

public function delete(User $user, Location $location, User $model)
{
    return $user->id === $model->id
        && $user->locations->contains($location->id);
}

现在它就像一个魅力。