feknuolis feknuolis - 4 months ago 14
PHP Question

Mix two foreach. Notifications. Laravel

I have this code here:

$likes = Like::orderBy('created_at', 'desc')->paginate(10);
$comments = Comment::orderBy('created_at', 'desc')->paginate(10);


HTML:

@foreach($likes as $like)

@endforeach


How to implement
comments
foreach in the
likes
foreach so the output not appears like this: At first appears
likes
and then appears
comments
. I want to mix it so it could appear something like this:

Like Comment Like Comment Comment Like

It's like notifications going

How is this possible ?

Answer

The easiest thing to do would be merge the collections, then order them by created_at, then foreach on the new colleciton:

PHP:

$likes = Like::orderBy('created_at', 'desc')->paginate(10);
$comments = Comment::orderBy('created_at', 'desc')->paginate(10);

$notifications = $likes->merge($comments)->sortByDesc('created_at');

HTML:

@foreach($notifications as $notification)

@endforeach