Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cimrie's avatar

Repository Pattern and Laravel Guard (Authorization)

Hi,

I was hoping to see a video on using Laravel's Guard facade with the repository pattern. How to basically implement policies that depend on the object returned from a repository (if you were to choose just to return plain arrays from your repository for instance).

I am trying to refactor towards the Repository Pattern to make it easier for me to unit test, but I use Guard extensively in my application to check for user permissions.

Would be cool to know if others thought something like this might be useful for Jeffrey to talk about.

Thanks!

0 likes
3 replies
bobbybouwmann's avatar

I think you mean the Gate facade right?

In my mind I would check the permission and based on that call a function of the repository

if ($request->user()->can('see-all-posts', $posts)) {
    $postsRepository->getAll();
} else {
    $postsRepository->getAllForUserId($user->id);
}

Just a simple example but you get the idea ;)

1 like
cimrie's avatar

Hey!

Yep - sorry, the Gate facade. Let me excuse that blip with a difficult day at work frying my brain ;)

I get what you are saying and maybe I am overcomplicating it. I use something like this inside a UserPolicy class (utilised by the Gate facade):

public function show(User $user, User $attemptedUser){
        return ( $user->can('view.users') || ($user->can('view.users.self') && $user->id == $attemptedUser->id) );
    }

Obviously then you are calling the Gate facade like so:

if (Gate::denies('show', $attemptedUser)) {
    // ... do something
}

For some things you don't need that extra parameter though, so you can call the Policy like this:

Guard::denies('index', User::class )

(which in my case would check if they don't have the right to list all Users.

The problem is that I feel I have now littered my controller or other parts of the application with at least a string representation of the original model, rather than the repository.

This might just need a good 'look at the bigger picture' from my end but any input would be appreciated.

rifqi96's avatar

Almost 4 years now, any updates on this case ? I'm facing about the same issue. I don't feel right to inject User object into each method in Policy classes. Or is there any way to change the injected parameters of policy class methods to use Repository/Service instead? Thanks in advance

Please or to participate in this conversation.