Skip to main content

User Roles and Permissions Protection

Premium
8 min read

In this lesson, permissions will be managed on the front and back end. We will again pass the permissions to React using the shared data Middleware.


Laravel Inertia Middleware

So, in the HandleInertiaRequests Middleware, you pass the permissions. Those permissions can come from some package or your own custom implementation. For example, let's add two permissions.

app/Http/Middleware/HandleInertiaRequests.php:

class HandleInertiaRequests extends Middleware
{
// ...
 
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message')
],
'user' => [
'name' => $request->user()?->name,
'email' => $request->user()?->email,
],
'permissions' => [
'posts_view' => true,
'posts_manage' => true,
],
]);
}
}

React Component Props

Next, we can add permissions as props instead...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

A
anjanesh ✓ Link copied!

Is there a separate article / tutorial on how to map posts_view and posts_manage dyamically based on a table with each user -> action authorization mapping ?

    protected function permissions(): Attribute
    {
        return Attribute::make(
            get: function () {
                return [
                    'posts_view' => in_array($this->id, [1, 2]),
                    'posts_manage' => $this->id == 1,
                ];
            }
        );
    }