mleontenko
5 months ago
211
1
Laravel

Return many to many relationship data to view

Posted 5 months ago by mleontenko

I have the following tables:

users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer

And many to many relationship:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
    }
}

I want to display a user with all his roles in view, so Controller looks like this:

public function show($id)
    {        
        $user = User::find($id);

        $roles= $user->roles();

        $user->roles= $roles;

        return view('users.show')->with('user', $user);
    }

The problem is there is in my view, if I print {{$user }}}, roles looks like this:

"roles":{
      "withTimestamps":false
   }

How can I make $user->roles contain data for each role in my view?

Please sign in or create an account to participate in this conversation.