yoann.celton+laracast@gmail.com's avatar

Use Laravel policies with anonymous users

Hi,

Is there a way in 5.1 to use policies without having a logged in user? To give an example, I would like to do something like that:

In a API-type app, different resources depends on a category. Most categories are public, but some are restricted. If the resource belong to a public category, anyone (included anonymous users) can see the content. However if the category is restricted, only a logged in user with proper credentials can see it.

In this use case policies are more usable than middleware, and the paths may vary, the category is not always a direct parent, etc. The issue is that if there's no user logged in, a 403 will be returned before even processing the policy, so I end up checking in the controller if the category is restricted, if so calling the policy, in which I check the restriction again. Very redundant. Any idea?

0 likes
4 replies
DigDoug's avatar

@krecebli I do not believe that will work. Before your "before" method is called, Gate.php tries to resolve a User and if it can't it throws an exception. See Gate::raw().

1 like
Qraxin's avatar

Actual for Laravel 9: you can use policies for guests. Policy method should have a User type parameter with null possibility or have default value as null. For example:

public function viewAny(User|null $user): bool

The conditions are described guest availability logic in class Illuminate\Auth\Access\Gate:

...
    protected function parameterAllowsGuests($parameter)
    {
        return ($parameter->hasType() && $parameter->allowsNull()) ||
               ($parameter->isDefaultValueAvailable() && is_null($parameter->getDefaultValue()));
    }
...

Please or to participate in this conversation.