laravel/nova-issues

BelongsToMany relation not fully respect policy rules in attach

freebuu opened this issue · 5 comments

  • Laravel Version: 10.39.0
  • Nova Version: 4.32.12
  • PHP Version: 8.1.2
  • Database Driver & Version: Postgres 16
  • Operating System and Version: MacOS
  • Browser type and version: Safari 17.3.1

Description:

I found a (possible) bug in the way BelongsToMany works. In the policy I created a condition like

    public function attachAnyGame(User $user, Model $model): bool
    {
        if ($model->games()->count() > 6) {
            return false;
        }

        return true;
    }

It works, the Attach button disappears if it is exceeded limit of 6.

However, if you use the Attach & Attach Another functionality, then the policy does not work and you can add it endlessly.

Detailed steps to reproduce the issue on a fresh Nova installation:

  • Add BelongsToMany relation field
  • Create policy for attaching this relation (like upper example)
  • Try to attach relations with Attach & Attach Another

Expected Behavior

When clicking Attach & Attach Another - the policy checks the conditions and returns 403 if policy return false

@crynobone any news? Maybe you need more info?

This feel a chicken vs egg scenario. Policy is not able to predict that adding 2 new records is not allowed. It can only check if we attempting to create a record.

But why policy don't check conditions AFTER i press the Attach button? In my opinion, this is two separate scenarios:

  • check policy for show/hide buttons
  • check policy when button is pressed

For now only first scenario works.

As I said earlier, during button press it can only get the policy for current process and cannot predict if it can add another. Showing 403 as suggested above is not the ideal solution (possibly making the UX worst)

Understand. But current behavior is not ideal too - you have policy with some restrictions, but if user open attach screen - it completely not working.

My workaround now - use model creating callback, but this is bit ugly. Hope you can do something with this in your way!