'How to show many-to-many in table in Laravel - Inertia with React?

I have a query in my index() method that searches a datatable:

use Inertia\Response as InertiaResponse;

public function (Request $request) : InertiaResponse
{
         $search = $request->query('search');

        //* Allow admin access
        if(Gate::allows('is-admin')) return Inertia::render('Admin/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(),

        ]);
}

In my frontend, I have a show button that has an onClick() listener that sets the state of a particular record:

<button onClick={(e) => {
           setPerson({roles: [user.roles]});
           setShowData(true); /* sets the state of the modal to true */
           console.log(Object.values(user.roles));
      }}
>
       Show
</button>

This is what I get in the console:


[
      0: {id: 1, role: 'Admin', created_at: null, updated_at: null, pivot: {…}}
      1: {id: 2, role: 'Designer', created_at: null, updated_at: null, pivot: {…}}
      2: {id: 3, role: 'Cashier', created_at: null, updated_at: null, pivot: {…}}
]
 length: 3

/* This is a detail of one of the objects */
0:
    created_at: null
    id: 1
    pivot: {user_id: 26, role_id: 1}
    role: "Admin"
    updated_at: null

which I think is what I should be getting. But when I try to display the values in the modal {person.roles} it doesn't show, and when I try to use {person.roles.role} or use console.log(user.roles.role) it gives me a null with an error showing undefined. How can I display this data?



Sources

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

Source: Stack Overflow

Solution Source