Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DestinatioN's avatar

Custom relationship Method in Model

Hello guys, I´m new to laravel and trying to simplify my user friend relationship. At the moment in my User Model I have the following relationships

public function relationshipFrom()
{
   return $this->hasMany('App\UserRelationship', 'from', 'id');
}
public function relationshipTo()
{
   return $this->hasMany('App\UserRelationship', 'to', 'id');
}

Inside my UserRelationship Model

public function userFrom()
{
   return $this->belongsTo('App\User', 'from', 'id');
}
public function userTo()
{
    return $this->belongsTo('App\User', 'to', 'id');
}

In my opinion there could be a better way to access the friends by creating a friends method in the User Model But if I do something like this inside the User Model I'm getting this error " Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation "

public function friends()
 {
    return UserRelationship::where('from', $this->id)->where('to', '!=', $this->id)->orWhere('from', '!=', $this->id)->where('to', $this->id)->get();
}

How can I get this to work.

This are my 2 Tables user (id, name) user_relationship (id, from, to)

0 likes
4 replies
rwdevguy's avatar

Am i correct in saying that personOne can be friends with personTwo but personTwo doesn't have to be friends with personOne?

M4rk3tt0's avatar

I don't think it's the right approach. You need a Many to Many relationship with a pivot table.

Take a look at this tutorial

pmall's avatar

Why not using a many to many relationship?

DestinatioN's avatar
DestinatioN
OP
Best Answer
Level 1

@rosswilson252 that's not correct really correct in my real table is a column named status so User from request a relationship to user to and user to has to accept this

@M4rk3tt0 it is a kind of Many to Many relationship without an "redundant" table by storing each relationship twice

I didn't store records "redundant" into the database because each relationship is stored only once.

So if

User1 added User2 as a friend

User3 added User1 as a friend

A normal select for this would look like this

(Select `u`.* 
FROM user_relationship 
    LEFT JOIN `user` `u` ON `to` = `u`.`id`
WHERE `from` = 2)
UNION
(SELECT `u`.* 
FROM user_relationship
    LEFT JOIN `user` `u` ON `from` = `u`.`id`
WHERE `to` = 2)

Result:

User1 friends are User2 and User3

User2 friend is User1

User3 friend is User1

Something like this I want to do in my model to get the user friends

I found the solution by myself. Everything was alright with my logic but I had some mistakes with the type casts

Please or to participate in this conversation.