阅读(2010) (5)

Laravel 8 策略响应

2021-06-29 16:33:52 更新

到目前为止,我们只研究了返回简单布尔值的策略方法。然而,有时您可能希望返回更详细的响应,包括错误消息。为此,您可以从您的策略方法返回一个 AuthAccessResponse

use IlluminateAuthAccessResponse;

/**
 * 确定用户是否可以更新给定的帖子
 *
 * @param  AppModelsUser  $user
 * @param  AppModelsPost  $post
 * @return IlluminateAuthAccessResponse
 */
public function update(User $user, Post $post)
{
    return $user->id === $post->user_id
                ? Response::allow()
                : Response::deny('You do not own this post.');
} 

当从策略返回授权响应时,Gate::allows 方法仍然返回一个简单的布尔值;但是,你可以使用 Gate::inspect 方法来获得 Gate 返回的完整授权响应:

$response = Gate::inspect('update', $post);

if ($response->allowed()) {
    // The action is authorized...
} else {
    echo $response->message();
} 

当然,当使用 Gate::authorize 方法在未授权操作时抛出 AuthorizationException,授权响应提供的错误消息将传播到 HTTP 响应:

Gate::authorize('update', $post);

// 该动作授权通过..