I am currently trying to make a relation between 3 tables.
Users
uid
username
Groups
gid
groupname
GroupMembers
uid
gid
With eloquent ORM, how do I get the Groups of a User?
With just 1 line of query I wanted to return a json reply like: (search group that I am a member of... keyword: Admin)
Status 200
User uid 1
username mrwootwoot
Groups
{
gid 1
groupname administrators
}
{
gid 2
groupname wadmin
}
What I got so far is:
$joined_networks = User::whereHas('groups', function($q)
{
$q->where('is_blocked', '=', 0)->where('name','like',"%admin%");
})->with('groups')->where('uid', $user_id)->get();
(...)
return Response::json(array(
'status' => 200,
'user' => $joined_networks->toArray()
));
This part of the code is suppose to find the groups the user is a member of where he is not blocked.
update
$joined = User::with('group')->where('uid', $user_id)->get();
return Response::json(array(
'status' => 200,
'results' => $joined
));
and my user model:
public function group()
{
return $this->hasManyThrough('Group', 'GroupMembers', 'uid', 'gid');
}
Now it just returns nothing
{
"status": 200,
"results": {
}
}
update
$user = User::find($user_id);
$user_groups = $user->groups();
return Response::json(array(
'status' => 200,
'results' => $user_groups
));
But still the same as above, no result being given back.
update It was a mistake on the output. $user_groups->toArray() is the right one. Works well now.