best practice to define several gates that checks over the same thing

34 Views Asked by At

I have created several gates in AuthServiceProvider and it's working as expected. However I'm curious about the efficiency of the code because some gates are checking the same thing, added with one or two additional checks. Here are some examples:

// Authorize user to 'open-page-one' if it has `foo` relationship
Gate::define('open-page-one', function (User $user) {
    return $user->foo()->exists();
});

// Authorize user to 'open-page-two' if if has `foo` relationship
// AND `foo` has `status` of true
Gate::define('open-page-two', function (User $user) {
    $foo = $user->foo;
    return $foo instanceof Foo && $foo->status === true;
});

As you can see, both gates are checking the same thing: does currently authenticated user has foo. However, the open-page-two needs to do an additional check.

The pattern above exists in other gates as well, not just one. I don't think that the code is not good in terms of efficiency because it runs the same query to retrieve foo several times. So back to the question: what is the best practice for such condition? Is it good enough already?

I'm actually thinking about retrieving foo directly inside AuthServiceProvider's boot method to a variable, and then use it repeatedly in all the necessary gates. But I'm not sure if that is a good practice.

Your help is much appreciated!

0

There are 0 best solutions below