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

vincent15000's avatar

Use a policy with only the model id and avoiding N+1

Hello,

Hmmm ... I wonder how I could use a policy with only a model id.

Gate::authorize('update', $model_id);

Sure this way it can't work because the Gate doesn't know the model.

What could be a solution to do that ?

Thanks for your help.

V

0 likes
3 replies
martinbean's avatar

Hmmm ... I wonder how I could use a policy with only a model id.

@vincent15000 That would be absolutely useless. If you call the gate using something like $this->can('update', 1); then how is Laravel supposed to know which model that 1 relates to? 🤷‍♂️

Stop over-thinking things and just use Laravel’s features as they’re documented.

1 like
vincent15000's avatar

It was so simple, but I didn't think about it.

To avoid N+1 problem, I just have to handle authorizations like this.

Instead of adding @can('update', $model) directly in the blade view, I can prepare the authorizations backend side.

$can_update = auth()->user()->can('update', $model);

And use this variable in the blade view.

@if ($can_update)
	...
@endif

I do this inside the Livewire component.

But doing like this, the authorization isn't refreshed automatically, I necessarily have to refresh manually the browser to see the authorizations displayed correctly.

Please or to participate in this conversation.