Reputation: 4058
I have a user model that have a relationship "many to many" with a role model. User model:
class User extends Model
{
...
public function roles()
{
return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), 'user_id', 'role_id');
}
}
I have a User controller, that have a method for getting user data in JSON format:
class UserController extends Controller {
...
// GET /user/3
public function show(User $user)
{
// $user is a single user
// return single user's data without roles
// I want to get user WITH roles
return $user;
}
// GET /users
public function index(User $user)
{
// returns list of users with roles.
$user->with('roles')->get();
}
}
The method show()
returns user's data without roles in JSON format. How to get user's data with roles data?
For list (index() method
) of users I can return users with roles using with()
method, but I don't know how to do it in show() method
return dd($user)
in show()
method outputs:
User {#192 ▼
#fillable: array:7 [▼
0 => "name"
1 => "email"
2 => "password"
3 => "username"
4 => "first_name"
5 => "last_name"
6 => "is_guest"
]
#hidden: array:2 [▼
0 => "password"
1 => "remember_token"
]
#totalCount: null
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:11 [▼
"id" => 11
"username" => "some_username6"
"email" => "[email protected]"
"password" => "$2y$10$h8mN6r8rWdiXv9VJG5z7NucaOrD9kEtfBSXnL6BdJGzV1671EkdaG"
"name" => "some name6"
"first_name" => "some_first_name6"
"last_name" => "some_last_name6"
"remember_token" => null
"created_at" => "2016-09-02 19:14:46"
"updated_at" => "2016-09-02 19:14:46"
"is_guest" => 1
]
#original: array:11 [▼
"id" => 11
"username" => "some_username6"
"email" => "[email protected]"
"password" => "$2y$10$h8mN6r8rWdiXv9VJG5z7NucaOrD9kEtfBSXnL6BdJGzV1671EkdaG"
"name" => "some name6"
"first_name" => "some_first_name6"
"last_name" => "some_last_name6"
"remember_token" => null
"created_at" => "2016-09-02 19:14:46"
"updated_at" => "2016-09-02 19:14:46"
"is_guest" => 1
]
#relations: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
Upvotes: 0
Views: 5270
Reputation: 2556
Use the load function in the show method:
class UserController extends Controller
{
public function show(User $user)
{
return $user->load('roles');
}
public function index(User $user)
{
return $user->with('roles')->get();
}
}
Upvotes: 4
Reputation: 180176
You can use the load
function on an existing model object to load a relationship's data.
$user->load('roles')
return $user;
Upvotes: 5