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

webfuelcode's avatar

Getting the category and posts inside it

Working on a directory where I want to display category and few numbers of posts inside that category.

Category and link facades are added to the controller. It is working fine to display list of categories and a list of links on the homepage.

My main concern is to use the relationship to get the category and a few lists from that category.

Actually it is a design concern, where I want the home page to show 3-4 categories and few links. It would a table or bootstrap card where the category name will appear on top and the list.

I am not sure to use the relation. Nothing much complicated I have just used a category and links relationship.

0 likes
3 replies
automica's avatar

@webfuelcode so Category hasMany Link?

do the following in your blade to get category name and links

<h2>{{$category->name}}</h2>
<ul>
@foreach($category->links as $links)
<li><a href='/{{$link->path}}'>{{$link->name}}</a></li>
@endforeach;
</ul>
webfuelcode's avatar

@automica I tried this and I think this is to display one single category and its listings in a page.

Where my purpose is to display 3-4 category (or a few chosen) with limited listings. Something like this... category

SilenceBringer's avatar
Level 55

Hi @webfuelcode If your target is to minimize the count of db calls, I can't imagine another way than using unions here, like so:

$postsQuery = null;

$categories = Category::take(5)->get();

$categories->each(function ($category) use (&$postsQuery) {
    $query = Post::where('category_id', $category->id)->take(5);

    $postsQuery = $postsQuery ? $postsQuery->union($query) : $query;
))

$posts = $postsQuery->get()->groupBy('category_id');

and then in your view file you can use it like

@foreach ($categories as $category)
    <div>{{ $category->name }}</div>

    @if ($posts->has($category->id))
        <ul>
            @foreach ($posts->get($category->id, []) as $post)
                <li><a href="{{ $post->url }}">{{ $post->title }}</a></li>
            @endforeach
        </ul>
    @endif
@endforeach

this way you'll have just 2 db calls

Please or to participate in this conversation.