Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MooseSaid's avatar

How to pass posts from two different sources to the same blade view but to be sorted by date

Headline seems a bit complicated but It's simple. I have a Post model with table and everything, in the PostController I'm passing posts to the view as below

Here in my controller I'm getting my articles from API and passing it to $articles variable and I'm getting my posts from database and I'm passing it to $posts variable

    public function index()
    {
        $articles = Http::withHeaders([
            'api-key' => config('services.devto.key'),
        ])->get('http://dev.to/api/articles/me/published');

        $articles = json_decode($articles, true);

        return view('posts.index', [
            'posts' => Post::latest()->filter(request(['search', 'category', 'author']))->paginate(6)->withQueryString(),
            'articles' => $articles
        ]);
    }

I can pass both to the same view and do as below and it works fine

            <div class="lg:grid lg:grid-cols-3">
                @foreach ($posts->skip($posts->onFirstPage() ? 3 : 0) as $post)
                    <x-postCard :post="$post" />
                @endforeach
                @foreach ($articles as $article)
                    <x-articlepostcard :article="$article" />
                @endforeach
            </div>

This gives me 6 of my posts because i paginate them and then right after i get all 10 articles from my API and then in page 2 i get another 6 of my posts and below them the same 10 articles repeated again because i can't paginate them as they're just json in a variable.

Any ideas on how to make my view show posts and articles altogether paginated and sorted by date?

0 likes
4 replies
midnightcipher's avatar

Note not tested, but I assume something along the lines of this. You would merge into a collection on your controller then paginate it and display it. Why not have an articles model that pulls from your dev.to api via artisan command and saves in local table, this way your pages won't die if https://dev.to/ decides to go down.

$articles = collect(json_decode($articles, true));
$posts = Post::latest()->filter(request(['search', 'category', 'author']));

$articlesAndPosts = $articles->merge($posts)->paginate(6)->withQueryString();
1 like
MooseSaid's avatar

@ashbakernz Can you help me more please? You mean create a Model for Articles to fetch my articles from API and store them in database? And you suggest this to be done as a custom artisan command?

Please or to participate in this conversation.