'Laravel - Jetstream (InertiaJS) - using guards in the top header menu (AppLayout.vue)

How can I use guards to add a specific admin menu entry using guards? I know I can pass guard-"data" from controllers to view like in the docs mentioned:

class UsersController extends Controller
{
    public function index()
    {
        return Inertia::render('Users/Index', [
            'can' => [
                'create_user' => Auth::user()->can('users.create'),
            ],
            'users' => User::all()->map(function ($user) {
                return [
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'email' => $user->email,
            //THIS BELOW IS THE GUARD-DATA
                    'can' => [
                        'edit_user' => Auth::user()->can('users.edit', $user),
                    ]
                ];
            }),
        ]);
    }
}

The question here is where is the controller for the AppLayout.vue file so I can accomplish this?



Solution 1:[1]

In this case i'll suggest you to share guards/permissions through HandleInertiaRequests.php file. I have used spatie/permissions to manage middlewares.

public function share(Request $request)
{
   return array_merge(parent::share($request), [
    'auth' => [
       'user' => [
           'id' => $request->user()->id ?? '',
           'name' => $request->user()->name ?? '',
           'permissions' => $request->user() ? 
           $request->user()->getPermissionNames() : '',
        ],
    ]
}

You can easilly access this data in vue template as $page.props.auth.user.permissions.

<template>
  <div v-if="can('edit-post')">
   //Edit Post
  <div>
<template>

<script>
  methods:{
    can(permission){
     // Check Permissions
     let data = this.$page.props.auth.user.permissions
     .filter((ability) => ability === permission);
      return data.length > 0 ? true : false;
    }
  }
<script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bikalpa