Josh
Josh

Reputation: 431

Possible to register a Laravel policy without a model?

I'm working on a Laravel project that leverages policies for authorization, and this works well when I'm authorizing an entity that has a corresponding model. However, not every entity I want to authorize has a corresponding model.

Is there a way to register a policy without a model (or is that fundamentally incorrect?), or should I take a different approach?

Upvotes: 2

Views: 2419

Answers (3)

mohammad aghandeh
mohammad aghandeh

Reputation: 157

assume we need to have custom policy without any attached models(CustomPolicy).

in AuthServiceProvider.php

protected $policies = [
    'custom_policy_name' => CustomPolicy::class
];

in controller

$this->authorize('methodNameInCustomPolicyClass', 'custom_policy_name')

Upvotes: 1

ChrisM
ChrisM

Reputation: 42

You can think of Policies as when using Resource in routes; there must be a corresponding model. Otherwise just spell it out with the Gates

Upvotes: 1

LobsterBaz
LobsterBaz

Reputation: 2003

You can with Gates, not with Policies.

  • Policies are classes that organize authorization logic around a particular model or resource.
  • Gates are useful to manage authorizations for business logic that don't involve a particular model or resource.

Here is Laravel documentation about Gates:

Upvotes: 6

Related Questions