Skip to content
Advertisement

Possibility using gate authorization without logged user

Is there a possiblity to use Gate authorization without making use of user auth service?

For example I want to define a Gate:

Gate::define('morning', function(){
    return date('H') < 12;
});

When I do Gate::allows('morning') or in the controller $this->authorize('morning') is returning always false because there is no user logged in.

How can I make this work for just guest users?

Advertisement

Answer

Although there may be better solutions like using middleware or using abort helper function:

abort_if(date('H') < 12, 403, 'This action is unauthorized.');

But there is solution for policies by declaring an “optional” type-hint or supplying a null default value for the user argument definition:

class DatePolicy
{
    /**
     * Determine if it's morning now!
     *
     * @param  AppUser  $user
     * @return bool
     */
    public function morning(?User $user)
    {
        return date('H') < 12;
    }
}

It may work for gates too but I haven’t test this:

Gate::define('morning', function ($user = null) {
    return date('H') < 12;
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement