Reputation: 3
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:
php artisan make:policy ProfilePolicy
( without model )AuthServiceProvider
in $policies
propertyedit
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
Reputation: 3022
In the controller you can write this
public function edit(Profile $profile) {
$this->authorize('edit', $profile)
}
Laravel does this:
$profile
, and it's a Profile::class
edit
method in that policy, if not found, return false meaning user is not authorizededit()
function that returns true/falseIn 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