Friday, March 3, 2017

can't find a way to count likes in post upon new like / dislike button is hit (laravel)

I have a like system in my project, while I am perfectly able to get likes count for posts from the user feed controller like this:

public function getFeed()
    {

        $user = Auth::user();

        $followedPosts = $user->getFollowedPosts();

        return view('user.feed', ['posts' => $followedPosts ]);


    }

where the method getFollowedPosts() is defined in the User Model like this:

public function getFollowedPosts()
    {
        $followedUsers = $this->followedUsers()->pluck('publisher_id')->toArray();

        $followedPosts = Post::with('likesCount', 'likes')->whereIn('user_id', $followedUsers)->orderBy('created_at')->with(['comments' => function ($query) {
            $query->latest();
            $query->with('author');
        },

            'user' => function ($q) {

                $q->select('id', 'username');
            }])->get()->reverse();

        return $followedPosts;
    }

which uses the likesCount() method that I have defined in the Post model like this:

public function likesCount()
    {
        return $this->likes()
            ->selectRaw('post_id, count(*) as aggregate')
            ->groupBy('post_id');
    }

and then I can access in the blade view like this:

@foreach ($posts as $i)

    

@endforeach

I am not able to retrieve the count if I do like this in my like function:

public function likePost($id)
    {   

        $post = Post::find($id);

         $postLikes = $post->likesCount();

         dd($postLikes[0]->aggregate);


        }

    }

error returned is:

FatalErrorException in PostController.php line 242:
Cannot use object of type Illuminate\Database\Eloquent\Relations\BelongsToMany as array

Question is, how do I get the count for the single post then? Any clue?



via Chriz74

Advertisement