Dynamic model binding in trait function

I have multiple Policy classes.

and these policies’ update, delete, restore functions have the same logic evaluation which is to check if the authenticated user owns the resource.

For example, I have a Post and a Comment model.

Then for PostPolicy and CommentPolicy, both of their update, delete, restore functions will all have:

public function update(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

public function delete(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

public function restore(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

// Also the same with CommentPolicy

With that, I might as well have a trait like this:

trait AuthorizableTrait
{
    public function authorize(User $user, Resource $resource)
    {
        return $user->id == $resource->user_id;
    }

}

So, my question is, is it possible to inject a dynamic instance of the current model inside the trait, for example, Post and Comment models now will become Resource? if so, how?

>Solution :

If you don’t specify the type of the authorize function second parameter, I think it will be all right.

If you define the following function, without the Resource type:

public function authorize(User $user, $resource)

You will be able to send everything you want in $resource (a post, a comment, etc.) and then the check will work… unless you always have a user_id attribute.

Leave a Reply