In my database I have two models, User and Role defined as many-many relationship, I'm trying to write a code in laravel that takes the id from the roles table and gets all the user fullnames from the users table.
I have defined a route that looks like this :
Route::get('roleUser/{role}', 'RoleController@RoleNames');
in which i pass the role name with it, as you see above
In my RoleController, I defined the method roleNames to do the job
public function RoleNames($role)
{
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->first()->id;
$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(array('id'));
$usersUnderRole = array();
foreach ($iduser as $idusers) {
$usersUnderRole = array_add($usersUnderRole, $idrole, $idusers);
$full_name = DB::table('users')->where('id', '=', $idusers)->get()->full_name;
}
return $this->respond([
'result' => $this -> roleTransformer->transform($full_name)
]);
}
This code is meant to take the role_id
from the roles
table and gets the appropriate user_ids
by the pivot table assigned_roles, puts them in an array and fetches the correspondent full_names
, but it says this error:
- Object of class stdClass could not be converted to string
Any advice on how to get it to work?
Besides the solution @lamzazo provided, there is another way to go with the answer :
$role2 = Role::where('name', '=', $role)->first();
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole);
$user = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get();
// $user = DB::table('users')->where('id', '=', $iduser);
// return $this->respond($iduser[0]->user_id);
$userArray = array();
$i=0;
foreach ($user as $users) {
$iduser= $users->user_id;
$allusers = User::where('id', '=', $iduser)->get(array('id', 'full_name'));
$userArray = array_add($userArray, $i . '', $allusers);
$i++;
}
return $this->respond([
'result' => $this -> roleTransformer->testTransform($role2, $userArray)
]);