So I have a Post which has Comments — I’m trying to get the Comment # position within that post. For example, a Post has 15 comments, I want to be able to get the numerical position (i.e 1 (first post), 2 (second post), 3 (third post), etc, etc), and put this into a function somehow. That way when I can call $comment->position() and it will show as the 4th, 5th, whatever position in it is in.
I’ve done some searching around the web and couldn’t find a solution. Any help is greatly appreciated! This is what I have so far:
public function position($id,$arr) { $total = $this->post->comments->count(); $position = $this->pluck('post_id')->search($this->id) + 1; return ceil($total / $position); //$comments_per_page = 25; //$pos = array_search($id,$arr); //$pos = $pos+1; //return ceil($pos/$comments_per_page); }
Advertisement
Answer
You should first get all your comments as collection.
// all comments as collection $comments = $this->post->comments;
Then you can search through the collection using the search
function and inserting an id
you want to search for … or any other param you want.
$id = 2; $commentIndex = $comments->search(function($comment) use ($id) { return $comment->id === $id; });