Friendship between users in Laravel 4 - php

I have created model so that users can be friends. I have table user_friends where user_id and friend_id are stored. The problem is, that it works only one-way. If user 1 adds user 2 as friend, user 2 will be friend of user 1 but not reverse (user 1 friend of user 2) how can I accomplish something like this?
User model
public function friends()
{
return $this->belongsToMany('User','user_friends','user_id','friend_id');
}
and User_Friend model
public function user()
{
return $this->belongsToMany('User');
}
Finding friends
$friends = User::find($user->id)->friends;
And part of controller where I save new friendship
$friendData = array('user_id' => $invite->id,); //$invite is result of $invite->save()
$friend = User::find($user->id)->friends()->attach($friendData);

One thing you can do is store and the reverse relationship.
$friendData = ['user_id' => $invite->id];
$user = User::find($user->id);
$user->friends()->attach($friendData);
$friend = User::find($invite->id);
$friend->friends()->attach($user);
Otherwise you may retrieve the reverse relationship
public function reverseFriends()
{
return $this->hasManyThrough('User', 'User_Friend', 'friend_id', 'user_id');
}
and then merge the two collections.

Related

Laravel: How can I get my friend relationship in a Pivot belongsToMany relation

I want to create a friendship relationship with another user in Laravel and when fetching the relationship, I want to get the user that isnt myself. (either user_id or friend_id)
This is the relationship I have:
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id')
->where('user_id', $this->id)
->orWhere('friend_id', $this->id);
When I am the user_id, I get the friend related
foreach($user->friends as $friend) {
echo $friend->first_name;
}
But when I am the friend, I get my own name. How can I solve this?
Thanks
You need two relations like below.
public function friends()
{
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
}
public function isFriendsWith()
{
return $this->belongsToMany(User::class, 'friend_user', 'friend_id', 'user_id');
}
Say a user with id 1 has two entries in the friend_user table like
id
user_id
friend_id
1
1
5
2
1
2
Then you can query relations like
$user1 = User::findOrFail(1);
$user1->friends; //Will get two users with an id of 2 and 5
$user2 = User::findOrFail(2);
$user2->isFriendsWith; //Will get one user with an id of 1
$user2->friends; //Will return empty collection
$user5 = User::findOrFail(5);
$user5->isFriendsWith; //Will get one user with an id of 1
$user5->friends; //Will return empty collection

Laravel (Eloquent)

I want to know how to make relationship using laravel Model & Eloquent.
I have data structur something like this
UserTable
username
groups
id
GroupTable
id
name
remark
My question is how to display user groups (user can assign to many groups)
and how to count how many users that assigned to each group.
thanks.
Update
public function store(Request $request){
$member = new Member();
$member->username = $request->input('name');
$member->gender = $request->input('gender');
$member->joindate = $request->input('joindate');
$member->remarks = $request->input('remarks');
if ($request->hasFile('photo')) {
if ($request->file('photo')->isValid()) {
$path = $this->upload($request);
}
}
$member->save();
foreach ($request->only('groups[]') as $key => $group){
$pivot = new pivot();
$pivot->user_id = ????? //how to get user id?
}
}
public function upload(Request $request)
{
$path = $request->file('photo')->store('profile');
return $path;
}
is that right?
and how to get currently saved user_id (it has auto increment column).
You will need to create a pivot table assigning each user to their respective groups.
so basically your tables would be like:
User Table
id
username
Groups Table
id
name
remark
User -> Group Pivot Table
user_id
group_id
Then you can use an Eloquent relationship on your user model to define your relational method like so:
class User extends Model {
public function groups() {
return $this->belongsToMany(Group::class, 'user_group_pivot_table_name', 'user_id', 'group_id');
}
}
Finally, you can return a collection of all the user’s groups by doing the following:
$user->groups();
The Laravel documentation on the Eloquent ORM is phenomenal too. Happy hunting.

laravel get relationship with multiple foriegn keys

I have three tables
Teams
id | Name
Winners
id | user_id | league_id
team_user
team_id | user_id | league_id
What I am trying to do in my Winner.php model is create a relationship that ties a winner to a team via the user_id and league_id
So basically I can call Winner->team and it will return the Team that the Winner belongs to where the user_id and league_id all match.
I was thinking
public function team()
{
return $this->belongsTo('App\Team', 'user_id', 'league_id');
}
But that doesnt work obviously. I am scratching my head since I have all the info I need to get the team associate to that league_id and user_id.
if your winner model returns multiple team use below code:
public function teams()
{
return $this->belongsToMany('App\Team', 'user_id', 'league_id');
}
if your winner model returns only one team use below code:
public function team()
{
return $this->belongsTo('App\Team', 'user_id', 'league_id');
}
Note:Here 3rd parameter in belogsTo() specifying your parent table's custom key
You can attach additional where() clause:
public function team()
{
return $this->belongsTo('App\Team', 'user_id', 'user_id')->where('league_id', $this->league_id);
}
Note: This will work with lazy loading only. Look here, it may help you.
I just used this as a function and not a relationship and looped through in my controller. not the best but all I got to work:
Winner.php
public function team()
{
$team_id = DB::table('team_user')
->where('league_id', $this->league_id )
->where('user_id', $this->user_id )
->first()
->team_id;
$team = Team::find( $team_id );
return $team;
}
In my controller
foreach( $league->winners as $winner)
{
$winner['team'] = $winner->team();
}

Join query that gets members of a group, and then gets groups as query in Laravel

I have a website build in Laravel.
I have two tables - Groups and Group members.
For each group_member, the row in the table has id, group_id and user_id.
The groups have a name and a description.
When a user joins a group, a row is created in the group_member table.
But I now need to get the groups that a user is part of.
So if I have user_id = 5, I need to get all the rows in group_member where user_id = 5, and then get the corresponding group, so I can query the groups.
I need to do something like $groups = Groups::whereGroup_member ...
But I cant query the model like that, because in Groups there is no where it specificies who the members are, it is just the group details - the members are specificed in group_member table.
How do I get the groups, which a member is part of using the laravel query standards?
In your User.php Model
public function group_member(){
return $this->hasMany(GroupMember::class,'user_id','id;);
}
In your GroupMember.php Model
public function group(){
return $this->belongsTo(Group::class,'group_id','id');
}
Your query will be
$users = User::with('group_member.group')->find($user_id);
You should use Many-to-Many relation:
class Group
...
public function members() {
return $this->belongsToMany(User::class); // Users (members) that belongs to Group
}
class User
...
public function groups() {
return $this->belongsToMany(Group::class, 'group_member', 'user_id', 'group_id'); // Groups that User belongs to
}
And at controller, when You have user id:
$groups = User::where('id', $user_id)->groups;
More about this written at official docs: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

How to write this in Eloquent to get list of Friends

I have a user's table for my application. I also have a pivot table for people who add other people to the application. I am trying to list out all the users that have been added by a user (1). How can I write this in eloquent?
Select u.* FROM users u join friend_user f ON u.user_id = f.friend_id where f.user_id = 1
I have it in a Friend model that presents the pivot table. Is it better to have a full query there or to create a friend function in the User and Friend class to show relationships?
<in User model> public function Friend(){ return $this->belongsTo('User'); }
If I understood you correctly, you should have the following in your User model:
public function friends()
{
return $this->belongsToMany('User', 'user_has_friends', 'user_id', 'friend_id');
}
Of course modify accordingly to your needs.
Now you can grab friends like this:
$user = User::find(1);
foreach($user->friends as $friend)
{
echo $friend->name .'<br>';
}

Categories