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

ersanserkan's avatar

Authorization for custom guard?

How can I use this policy helper method for custom guards?

$this->authorize('update', $model);
0 likes
7 replies
mikenewbuild's avatar

Might help to provide an example of the type of guard you want to make?

ersanserkan's avatar

This code worked for me.

$user = auth('admin')->user();

if ($user->can('update', $model)) {
    return true;
}

return false;

I wonder If I can do it with authorize() helper?

mikenewbuild's avatar

Hey @ersanserkan - I think there's a couple of ways, and it depends what you want to achieve.

You can add the logic in the update method of the policy for that model, or if you want it to apply to all methods of that policy, you can use the before method in the policy.

If you want it to apply to all policies, then you should be able to apply it in the boot method of AuthServiceProvider.

Something like

public function boot()
{
    $this->registerPolicies();

    Gate::before(function($user) {
        return $user->is(auth('admin')->user());
    });
}

(not tested)

ersanserkan's avatar

[SOLVED]

I found the solution by doing runtime config change.

config(['auth.defaults.guard' => 'admin']);

$this->authorize('update', $user);

I wish I would use $guard name as third parameter in $this->authorize() helper..

1 like
ersanserkan's avatar

This one also works for custom guard

$this->authorizeForUser($user, 'update', $model);
FlashWalker's avatar

This fixed my error

Route::prefix('master')->middleware('auth:admin, auth.admin')->group(function () {
	
});

By simply adding this middleware to my route group 'auth:admin' i was able to make the routes in the group load use the admin guard i created as their default.

1 like

Please or to participate in this conversation.