laravelpolicyjson-api

Laravel JSON:API - Allow users to create objects related only to themselves


I have a JSON API set up where I would like to allow users to only create addresses for themselves.

In the docs it shows that there is no request to check against in the Policy when creating a resource.

The relationship validation also only works for updates, not for creation, so I can't quite see how I could say "only authorise users to create an address if the relationship is to their own user ID" in a similar way to the update methods.

Example Policy:

class AddressPolicy
{
    use HandlesAuthorization;
    
    public function update(User $requestingUser, Address $address): bool
    {
        // User may update their own address if they do not have permission to edit all addresses
        return  $requestingUser->is($address->user) || $requestingUser->can('edit addresses');
    }

    public function create(User $requestingUser): bool
    {
        // Check if requestingUser is creating an address for themselves?
        return $requestingUser->can('create addresses');
    }
}

The only option I can see is to create a custom controller action for this, but it feels like it should be possible to do this via Policy validation or similar.


Solution

  • I ended up adjusting the permissions and implementing a solution in an Address controller:

    if ($currentUser->getKey() === $creatingForUserId && $currentUser->can('create own addresses')) {
        return;
    }