Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading