Generally It is a bad idea to merge data of completely different types. What are you trying to do here? Seems a better approach is just two foreach() statements
Merging data from 2 collections in an activity feed
Hello, I am trying to build an activity feed of authors, or users activity on the blog I am creating as part of a practice exercise.
If I have a collection for 'comments' & a collection for 'posts' that are both related to the user model eg.
$user->posts
$user->comments
How do I go about creating an activity feed that allows me to combine the 2 collections when the data is output in the view so that they are organised in desc date order?
I assume it might be something along the lines of the following but would like your assistance.
$allItems = new \Illuminate\Database\Eloquent\Collection;
$allItems = $allItems->merge($user->posts);
$allItems = $allItems->merge($user->comments);
Then in the view, something like
@foreach($allitems as $allitem)
//if an item contain the contents of a post use this html formatting
// else and item is a comment & use different html
But I don't fully grasp or understand how I would then have different UI for comments & posts, as I commented, maybe an if statement that looks at the instance of the collection and discerns whether it is a comment or a post?
I am not sure, I appreciate any advice.
@CamKem If you have the actual classes you can check the try and return a matching type of component
@if ($item instanceof \App\Models\Post)
<x-post :post="$post" />
@elseif ($item instanceof \App\Models\Comment)
<x-comment :comment="$comment" />
@endif
Please or to participate in this conversation.