Not sure if this is exactly what you are after, but I would do try this:
Route::get('/test', function () {
$userId = Auth::id();
// dynamic relation
Post::resolveRelationUsing('related', fn ($model) => $model->morphTo('related'));
$records = Post::query()
->with(['related'])
->select([
'id AS related_id',
DB::raw(sprintf(
'"%s" AS related_type',
str_replace('\\', '\\\\', (new Post())->getMorphClass())
)),
'created_at',
])
->where('user_id', $userId)
->union(
PostComment::query()
->select([
'id AS related_id',
DB::raw(sprintf(
'"%s" AS related_type',
str_replace('\\', '\\\\', (new PostComment())->getMorphClass())
)),
'created_at',
])
->where('user_id', $userId)
->toBase()
)
->orderByDesc('created_at')
->orderByDesc('related_id')
->orderBy('related_type')
->simplePaginate();
$records->getCollection()->transform(fn ($record) => $record->related);
return $records;
});
The trick here is that we are uniting both tables and ordering by the most recent ones.
The results act like a polymorphic model, and a dynamic relation is defined to allow eager loading the related models.
After paginating, we then unwrap the eager loaded models from the temporary relation.
Some references:
- https://laravel.com/docs/8.x/eloquent-relationships#polymorphic-relationships
- https://laravel.com/docs/8.x/eloquent-relationships#dynamic-relationships
Hope this helps you out.