strange behaviour with eloquent

Posted 2 years ago by nikocraft

In my controller I am doing this:

    public function comments(Request $request, $username)
    {
        $user = User::with(array(
                'comments.gallery.images' => function ($query) {
                    $query->orderBy('created_at', 'desc');
                }
            ))->with('comments.votes')->where('username', $username)->first();

        return view('user.comments')->withUser($user);
    }

in the view I do this:

<span>{{ $comment->getPointsAttribute() }} pts</span>

getPointsAttribute is a function in a Votable class, which is using polymorphics relationship

    public function votes(){
        return $this->morphMany(Vote::class, 'votable');
    }

    public function getPointsAttribute()
    {
        $points = 0;
        foreach ($this->votes AS $vote) {
            $points = $vote->status == 'upvote' ? $votes + 1 : $votes - 1;
        }
        return $points;
    }

when I load the page I get this:

ErrorException in Votable.php line 34: Undefined variable: votes

if I however in the view do this in the view:

<span>{{ $comment->votes }} pts</span>
[{"id":1409,"votable_id":365,"votable_type":"App\\Comment","user_id":22,"status":"upvote","created_at":"2016-08-17 20:23:27","updated_at":"2016-08-17 20:23:27"},

{"id":2662,"votable_id":365,"votable_type":"App\\Comment","user_id":28,"status":"upvote","created_at":"2016-08-17 20:27:38","updated_at":"2016-08-17 20:27:38"}]

it renders the votes as json array, so votes are there, why can't I access them inside the method getPointsAttribute() like this

$this->votes AS $vote

it works if I do it in the view. Really strange behaviour, any ideas?

Please sign in or create an account to participate in this conversation.