Reputation: 45
So I have two models like
and follow
models, and I want to create an activity page where the user can see his latest activity accordingly. I thought about merging the two models in the view using laravel's merge
function but I'm lost on how to indicate if a user liked the post or followed a blog.
$like= Like::where('user_id', '=', auth()->user()->id)->orderBy('created_at','desc')->get();
$follow = Follow::where('user_id', '=', auth()->user()->id)->orderBy('created_at','desc')->get();
$all = $like->merge($follow);
If I use an if statement in the view, it will group the different datas in the view rather than combining them together to make an activity timeline.
If you could help thanks
Upvotes: 0
Views: 146
Reputation: 50511
You can merge these collections together and order/sort them how you wish. I highly recommend not merging an Eloquent Collection into another Eloquent Collection of different types. Unlike the Base Collection type (Illuminate\Support\Collection
) which the Eloquent Collection (Illuminate\Database\Eloquent\Collection
) extends from it takes into account the models' keys. So if you have 2 collections and any models have the same key in them they will get overwritten. You want to convert one of these collections to a Base Collection then merge in the other one:
$merged = $like->toBase()->merge($follow);
$sorted = $merged->sortByDesc('created_at');
Or even convert them both to base Collections and merge:
$merged = $like->toBase()->merge($follow->toBase());
Upvotes: 1