This is maybe a question on how Laravel works internally.
I'm writting an app. Only a logged user can create certain kind of records, that's easy, you just add $this->middleware('auth')
to the controller, and that's it.
Now I want something more complex, the users with the role admin
can create/edit that kind of records on behalf of some user. Imagine something like StackOverflow where a user can edit the question another user made, but for creation. That's it, an admin can create a post on behalf of the user():
So I have my create()
in my PronController
, it is something like:
function create($sid, $uid=NULL) {
// $sid is section id, where the post is going to be created... don't mind...
// if $uid (user id) is null, it will take the user from Auth::user()->id
$user = empty($uid) ? Auth::user() : User::findOrFail($uid);
// I want that only "admin" can use this $uid parameter, so I plan to use
// a Policy:
$this->authorize('create', $user);
}
The policy in PronPolicy
is quite simple:
function create(User $authUser, User $user) {
return ($authUser->id === $user->id) || $authUser->isAdmin;
}
Now, I thought this should work, but it doesn't. It never reaches this edit()
(I placed Log's)
So what I did is to change the $this->authorize()
line to:
$this->authorize('createpron', $user);
And change the UserPolicy()
(The UserPolicy!!!) to:
function createpron(User $authUser, User $user) {
return ($authUser->id === $user->id) || $authUser->isAdmin;
}
Now this works as I wanted. But I don't know why. Looks like Laravel searches for the object type in the parameter and then it activates the policy for that parameter, is it correct?
I don't know, although my code is working, it seems to me a bit dirty since the create "Pron" should be a policy of Pron, not user. Am I doing something conceptually wrong? what would be the right way to implement this?