@emokores Can you please share the how did you implement the users roles relation in the database and the models ?
Show many-to-many (roles) in table - Inertia with React
I have a table that shows a list of users. Each user can be assigned more than one role. I would like to display the user roles in the column ROLES.
My backend:
use Inertia\Response as InertiaResponse;
public function index() : InertiaResponse
{
return inertia('Users/Index', [
'users' => User::query()->when($search, fn ($query) =>
$query->where('name', 'LIKE', "%{$search}%")->orWhere('email', 'LIKE', "%{$search}%")
)->orderByDesc('created_at')->paginate(10)->withQueryString(),
'roles' => Role::all(),
]);
}
In my frontend:
const { users, roles } = usePage().props, { data } = users;
return (
{data.map((user, index) => (
<tr key={index}>
<td>{user.name}</td>
<td>{/* TODO: userRoles */}</td>
</tr>
))}
);
I'm stuck on how to bring in to display the user roles for each user. I know I have to first declare it in the backend, then pass it to React to render it. But how??
I solved the issue. This is what I used in my index method:
//* index() method of the Users controller:
return inertia('Users/Index', [
'users' => User::query()->when($search, fn ($query) =>
$query->where('name', 'LIKE', "%{$search}%")->orWhere('email', 'LIKE', "%{$search}%")
)->with('roles')->orderByDesc('created_at')->paginate(10)->withQueryString()
]);
I then declared the Object.values(user.roles) object in a setState({roles: []}) method and mapped through the object's array with state.roles.map() to output the role names. I displayed this in a modal instead.
Please or to participate in this conversation.