Shioriu
Shioriu

Reputation: 3

Laravel policy autodetect

today i was creating USER profile page with is controlled in ProfileController it returning views to profile page, profile settings, etc.

so i decide to make some Policy rules to Edit profile and etc.

so i found i should use Middleware / Gates / Policy, based on Laravel Doc i chose Policy because profil page is public but only specific part of it can author edit so i needed @can

So my steps:

  1. php artisan make:policy ProfilePolicy ( without model )
  2. Registered policy to AuthServiceProvider in $policies property
  3. writed methods like edit inside ProfilePolicy

then i started thinking how i define it to my Controller hmmm, documentation doesnt helps me :/

so i tryed blade @can('edit', $user) method and it worked, but HOW ?, how to define specific policy to one Controller ? ( not Model ), how to define multiple Policy to single Controller

i m lost how laravel Magic done this maybe because of Naming ? ProfileController => ProfilePolicy ?

Upvotes: 0

Views: 1012

Answers (1)

Leonardo Rossi
Leonardo Rossi

Reputation: 3022

In the controller you can write this

public function edit(Profile $profile) {
   $this->authorize('edit', $profile)
}

Laravel does this:

  • Check the type of $profile, and it's a Profile::class
  • Check policies registered for that class (your step 2)
  • Looks for the edit method in that policy, if not found, return false meaning user is not authorized
  • Executes the edit() function that returns true/false

In blade the @can directive does exactly the same thing.

Policies are meant to be tied to Models, it's a convenient way to write rules to handle single models, but they can be triggered in many ways (like the authorize() method in controllers and @can directive in blade).

Upvotes: 1

Related Questions