-
-
Save Luizgpp/cc1a2b195c1361b5a1b35f80ecd77a72 to your computer and use it in GitHub Desktop.
Laravel: A Trait for friendship.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use App\User; | |
trait Friendship | |
{ | |
public function solicitationsOfMine() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id') | |
->wherePivot('accepted', false) | |
->withTimestamps(); | |
} | |
public function solicitationsOf() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'friend_id', 'user_id') | |
->wherePivot('accepted', false) | |
->withTimestamps(); | |
} | |
public function friendsOfMine() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id') | |
->wherePivot('accepted', true) | |
->withTimestamps(); | |
} | |
public function friendsOf() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'friend_id', 'user_id') | |
->wherePivot('accepted', true) | |
->withTimestamps(); | |
} | |
public function getFriendsAttribute() | |
{ | |
if ( ! array_key_exists('friends', $this->relations)) $this->loadFriends(); | |
return $this->getRelation('friends'); | |
} | |
protected function loadFriends() | |
{ | |
if ( ! array_key_exists('friends', $this->relations)) | |
{ | |
$friends = $this->mergeFriends(); | |
$this->setRelation('friends', $friends); | |
} | |
} | |
protected function mergeFriends() | |
{ | |
return $this->friendsOfMine->merge($this->friendsOf); | |
} | |
public function closeFriendsOfMine() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id') | |
->wherePivot('accepted', true) | |
->wherePivot('user_close', true) | |
->withTimestamps(); | |
} | |
public function closeFriendsOf() | |
{ | |
return $this->belongsToMany(User::class, 'friend_user', 'friend_id', 'user_id') | |
->wherePivot('accepted', true) | |
->wherePivot('friend_close', true) | |
->withTimestamps(); | |
} | |
public function getCloseFriendsAttribute() | |
{ | |
if ( ! array_key_exists('closeFriends', $this->relations)) $this->loadCloseFriends(); | |
return $this->getRelation('closeFriends'); | |
} | |
protected function loadCloseFriends() | |
{ | |
if ( ! array_key_exists('closeFriends', $this->relations)) | |
{ | |
$closeFriends = $this->mergeCloseFriends(); | |
$this->setRelation('closeFriends', $closeFriends); | |
} | |
} | |
protected function mergeCloseFriends() | |
{ | |
return $this->closeFriendsOfMine->merge($this->closeFriendsOf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment