Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sh1r3f's avatar

How to send frontend the state of authorization for each api resource?

I was working with inertia before and I was doing something great to tell my frontend part what is the authorization state (true or false) of a some kind of action for example; I've an index page that lists a paginated collection of Posts; And I've a PostPolicy that allows me to delete a post resource if I'm a superadmin or if it's my post. So, before I was sending the posts collection to my inertia frontend I was mapping through them setting $post->delectable = $user->can('delete', $post) so it become a true or false state in my frontend then I can use it to show or hide a delete button.

So this is the question! is there a way to provide this thing with API? I send the collection of paginated posts through PostResource::collection($posts). How can I implement the delete authorization state with each post resource sent through this collection? Please provide code examples with your solution! Thanks in advance.

0 likes
5 replies
edvinaskrucas's avatar

Hi,

Most straight forward solution could be implemented like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Gate;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return array_merge(parent::toArray($request), [
            'deletable' => Gate::allows('delete', $this->resource),
        ]);
    }
}

Just append your custom properties to resource response.

2 likes
sh1r3f's avatar

@edvinaskrucas Thanks for your solutions. I would love to ask is this the practical way to do it? I meant normally when you build your own projects API this is what you go for?

sh1r3f's avatar

@edvinaskrucas Also, what about basic authorization ? How would you tell the frontend that current user can't get access to view the posts index page? also users index, comments index, etc... How do you send these states?

edvinaskrucas's avatar

@sh1r3f yes, I use this solution, its easy enough to implement and does not depend on any package, so its easier to maintain and update your app in future for latest versions of Laravel. But I bet that there are some packages solving this issue. Just use whatever suits your needs best.

1 like
edvinaskrucas's avatar

@sh1r3f well, that depends on your whole frontend app setup. I do not have answer for that.

1 like

Please or to participate in this conversation.