Zia Yamin
Zia Yamin

Reputation: 1004

Property [id] does not exist on the Eloquent builder instance

I am trying to get comment and it's replies in laravel api,I tried following way and faced to this error, how can I solve it? this is my controller:

 public function postSinglePage(Request $request)
{
    $post_id=$request->get('post_id');
    $post = Post::where('id',$post_id)->where('status', '=', 1)->get();
    return response([
        "posts" => GetPostsSinglePageData::collection($post),

    ]);


}

and this is my resource collection to get post and it's comments:

public function toArray($request)
{

    return [
        'post_id' => $this->id,
        "name" => $this->post_title,
        "excerpt" => $this->post_excerpt,
        "thumbnail" => $this->getFirstMediaUrl("images"),
        "logo" => $this->getFirstMediaUrl("images"),
        'comment_count'=>getCommentCount($this->id),
        'comments'=> new CommentCollection(Comment::select('*')->where('post_id',$this->id)),
        "like" => DB::table("like_tb")->select('like_dislike')
            ->where("type_like",'=','post')
            ->where('related_id',$this->id)
            ->get(),
        "share" => DB::table("share_tb")->select("share_number")
            ->where('type','=','post')
            ->where("related_id",$this->id)
            ->get(),

    ];
}

this is comment collection:

public function toArray($request)
{


    return [
        'commentId'=>$this->id,
        'courseId'=>$this->post_id,
        'commentDate'=>$this->date,
        'commentText'=>$this->body,
        'userId'=>$this->user_id,
        'replays'=>ReplyCommentCollection::collection(\App\Models\Comment\ReplyComment::where('comment_id',$this->id)->get()),
        'users'=>UserInfoCollection::collection(User::where('id',$this->user_id)->get()),
    ];
}

Upvotes: 2

Views: 16255

Answers (1)

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

$this->id not work in inner other function you must write like this:

  public function toArray($request)
    {
        $comments=Comment::select('*')->where('post_id',$this->id)->get();
        $commentCollection= CommentCollection::collection($comments);
        return [
            'post_id' => $this->id,
            "name" => $this->post_title,
            "excerpt" => $this->post_excerpt,
            "thumbnail" => $this->getFirstMediaUrl("images"),
            "logo" => $this->getFirstMediaUrl("images"),
            'comment_count'=>getCommentCount($this->id),
            'comments'=> $commentCollection,
            "like" => DB::table("like_tb")->select('like_dislike')
                ->where("type_like",'=','post')
                ->where('related_id',$this->id)
                ->get(),
            "share" => DB::table("share_tb")->select("share_number")
                ->where('type','=','post')
                ->where("related_id",$this->id)
                ->get(),

        ];
    }

Upvotes: 1

Related Questions