I have a problem retrieving the role and permission data from authenticated users for implementing conditional rendering based on role and permission. this is my first time using react and laravel breeze so I'm confused about where or which controller provides the authenticated user data which is only basic data by default for auth variable, so i need to add some code to provide role and permission data also. please help me to figure this out.
let's see the code below
import React, { useState } from 'react';
import ApplicationLogo from '@/Components/ApplicationLogo';
import Dropdown from '@/Components/Dropdown';
import NavLink from '@/Components/NavLink';
import ResponsiveNavLink from '@/Components/ResponsiveNavLink';
import { Link } from '@inertiajs/inertia-react';
import Navbar from '@/Components/Navbar';
export default function Authenticated({ auth <--- //this auth variable, header, children }) {
const [showingNavigationDropdown, setShowingNavigationDropdown] = useState(false);
return (
<div className="min-h-screen bg-gray-100">
<nav className="bg-white border-b border-gray-100">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
<Navbar userData = {auth.user.name} method="post"/>
</div>
</div>
</nav>
{header && (
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">{header}</div>
</header>
)}
<main>{children}</main>
</div>
);
}
laravel breeze already provides us with a variable called auth which contains authenticated user data by default, so I need to add role and permission data to the variable.
Thank You in advance
CodePudding user response:
Inertia provides a middleware to define props that are shared by default (docs). Here, you may specify this roles that you are talking about.
Here I got a simplified example of one of my projects. I only retrieve the user's fields I need and their roles to be shared:
/**
* Define the props that are shared by default.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function share(Request $request)
{
$user = Auth::user();
if ($user) {
$user->load('roles');
$user = [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->roles,
];
}
return array_merge(parent::share($request), [
'auth' => [
'user' => $user ?? [],
],
'flash' => [
'success' => fn () => $request->session()->get('success'),
'error' => fn () => $request->session()->get('error'),
],
]);
}