Skip to content
Lex de Willigen edited this page Feb 11, 2021 · 4 revisions

Add abilities to Laravel API resources

If you build a web app with a separate frontend and backend, all kinds of information has to be transferred between these two parts. Part of this are your routes, but how do you share resource permissions in the most convenient way? We use API resources for this. That way we can see for each resource what permissions the current user has for that resource. However, when just adding the Gate::check(), a lot of gates may be checked which are not needed for that route. Therefore, this package gives you precise control over which gates exactly need to be checked. Let's take a look at such a resource:

class PostResource extends JsonResource
{
    use ProcessesAbilities;

    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'published_at' => $this->published_at,

            'abilities' => $this->abilities(PostPolicy::class)
        ];
    }
}

Our package will scan the PostPolicy for available methods and check whether the gate allows or denies the user a certain permission. As a result, the json output will look like this:

{
    "data": {
    "id": 10,
    "title": "Corporis eum adipisci et cum nostrum.",
    "slug": "corporis-eum-adipisci-et-cum-nostrum",
    "published_at": "2020-06-06T10:49:01.000000Z",
        "abilities": {
            "view": true,
            "update": false,
            "delete": true
        }
    }
}
Clone this wiki locally