Skip to content

Commit

Permalink
Fixed #161.
Browse files Browse the repository at this point in the history
  • Loading branch information
overtrue committed Jul 8, 2021
1 parent 793e8bc commit 2386dd5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/Followable.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,17 @@ public function attachFollowStatus($followables, callable $resolver = null)

\abort_if(!($followables instanceof Collection), 422, 'Invalid $followables type.');

$followed = $this->followings()->wherePivot('accepted_at', '!=', null)->pluck('following_id');
$followed = UserFollower::where('follower_id', $this->getKey())->get();

$followables->map(function ($followable) use ($followed, $resolver) {
$resolver = $resolver ?? fn ($m) => $m;
$followable = $resolver($followable);

if ($followable && \in_array(Followable::class, \class_uses($followable))) {
$followable->setAttribute('has_followed', $followed->contains($followable->getKey()));
$item = $followed->where('following_id', $followable->getKey())->first();
$followable->setAttribute('has_followed', !!$item);
$followable->setAttribute('followed_at', $item ? $item->created_at : null);
$followable->setAttribute('follow_accepted_at', $item ? $item->accepted_at : null);
}
});

Expand Down
4 changes: 4 additions & 0 deletions tests/FeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tests;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Overtrue\LaravelFollow\Events\Followed;
Expand Down Expand Up @@ -207,9 +208,12 @@ function () use ($user1, $users) {

$this->assertFalse($users[0]->has_followed);
$this->assertTrue($users[1]->has_followed);
$this->assertInstanceOf(Carbon::class, $users[1]->followed_at);

$this->assertTrue($users[2]->has_followed);
$this->assertTrue($users[3]->has_followed);


// with custom resolver
$posts = \collect(['author' => $user2], ['author' => $user3], ['author' => $user4]);
$user1->attachFollowStatus($posts, fn ($post) => $post['author']);
Expand Down

0 comments on commit 2386dd5

Please sign in to comment.