Created
June 2, 2018 02:32
-
-
Save ryanvade/2f98803028c7d3c94b7bc627ec7b447f to your computer and use it in GitHub Desktop.
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 Csb\Traits; | |
use Csb\User; | |
use Csb\Follow; | |
/** | |
* Trait Followable | |
* | |
* Created by Ryan Owens | |
* | |
* @package Csb\Traits | |
*/ | |
trait Followable { | |
/** | |
* Append to model Boot function | |
* | |
* Delete the 'follow' manually when the model is deleted | |
*/ | |
protected static function bootFollowable() { | |
static::deleting(function($model) { | |
$follows = $model->follows()->get(); | |
foreach($follows as $follow) { | |
$follow->delete(); | |
} | |
}); | |
} | |
/** | |
* Get a models Follows | |
* | |
* @return mixed | |
*/ | |
public function follows() { | |
return $this->morphMany(Follow::class, 'followable'); | |
} | |
/** | |
* Apply a 'follow' on the model from the given user | |
* | |
* @param User $user | |
* @return mixed | |
*/ | |
public function follow(User $user) { | |
$attributes = [ | |
'user_id' => $user->id, | |
'followable_id' => $this->id, | |
'followable_type' => get_class($this), | |
]; | |
if(!$this->follows()->where($attributes)->exists()) { | |
$this->follows()->create($attributes); | |
} | |
$this->save(); | |
} | |
/** | |
* Remove a 'follow' on the model from the given user | |
* | |
* @param User $user | |
*/ | |
public function unFollow(User $user) | |
{ | |
$attributes = [ | |
'user_id' => $user->id | |
]; | |
$this->follows()->where($attributes)->each(function($follow){ | |
$follow->delete(); // calls $favorite static::deleting() | |
}); | |
} | |
/** | |
* Check if the model has a 'follow' from the given user | |
* | |
* @param User $user | |
* @return bool | |
*/ | |
public function followed(User $user) | |
{ | |
$attributes = [ | |
'user_id' => $user->id | |
]; | |
return !! $this->follows()->where($attributes)->count(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment