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

vincent15000's avatar

Best pratice to access to the authorizations via InertiaJS

Hello,

I have read the documentation for the authorizations.

https://inertiajs.com/authorization

I have tried to do that.

$path->load('level', 'projects.level');
$path->projects->each(function ($project, $key) {
    $project->can_delete = auth()->user()->can('delete', $project);
});
return Inertia::render('Paths/Show', compact('path'));

But what about simplifying this and adding an appended property to the model ?

protected $appends = ['can_delete'];
...
public function getCanDeleteAttribute()
{
    return auth()->user()->can('delete', $this);
}

Is it a good idea and does it remain secure ?

Thanks for your answer ;).

V

0 likes
10 replies
Sinnbeck's avatar

It should still be safe. But personally I would not auto append it as you might not want it in every single query that uses the project model. Just append it when you need it

$path->projects->append('can_delete');
1 like
tykus's avatar
tykus
Best Answer
Level 104

It amounts to the same thing really, there will be a can_delete property available on the model instance. But the downside of this approach is you are mixing the HTTP layer with the model logic. You should be able to interact with the model without an authenticated user; but this approach bakes it in.

Personally I prefer Eloquent API resources for this because it represents the Model instance(s) but stays in the HTTP layer of the application.

1 like
vincent15000's avatar

@tykus Before using InertiaJS, I did this via the API resources and it was great to do so. Now using InertiaJS, I just test and try to find another way to pass the authorizations to the front.

tykus's avatar

@vincent15000 you still need to be very mindful of the data you are sending to the client-side application - and API Resources IMHO the best way to control that data, especially as an alternative to blindly serializing the Model directly, which is sensitive to changes in the database schema, property visibility and appended accessors on the Model - the Resource allows you to define a fixed structure that the client-side application expects

1 like
vincent15000's avatar

@tykus Ok yes I found the API resources very pratice because I was able to return exactly what I wanted and needed in the front.

I should try to continue using the API resources and send them via InertiaJS rendering.

Please or to participate in this conversation.