Laravel - Authorization - Policy Responses

So far, we have only examined policy methods that return simple boolean values. However, sometimes you may wish to return a more detailed response, including an error message. To do so, you may return an Illuminate\Auth\Access\Response instance from your policy method:

    
    use App\Models\Post;
    use App\Models\User;
    use Illuminate\Auth\Access\Response;
    
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Auth\Access\Response
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id
                    ? Response::allow()
                    : Response::deny('You do not own this post.');
    }
	

When returning an authorization response from your policy, the Gate::allows method will still return a simple boolean value; however, you may use the Gate::inspect method to get the full authorization response returned by the gate:

    
    use Illuminate\Support\Facades\Gate;
    
    $response = Gate::inspect('update', $post);
    
    if ($response->allowed()) {
        // The action is authorized...
    } else {
        echo $response->message();
    }
	

When using the Gate::authorize method, which throws an AuthorizationException if the action is not authorized, the error message provided by the authorization response will be propagated to the HTTP response:

    
    Gate::authorize('update', $post);
    
    // The action is authorized...