Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Created January 5, 2018 07:25
Show Gist options
  • Save sayhicoelho/ecc390a5987775a94b06f1e96d76209a to your computer and use it in GitHub Desktop.
Save sayhicoelho/ecc390a5987775a94b06f1e96d76209a to your computer and use it in GitHub Desktop.
Laravel: A Trait for friendship.
<?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