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

ufodisko's avatar

How can I retreive and display all posts that belong to a certain category

I have 3 tables

user: id, username..

subreddits: id, name, created_at..

posts: id, title, link, user_id, subreddit_id

The problem is, I am fetching the id of the subreddit/category manually while I need to be fetching it dynamically. How can I achieve that?

This is the show() method in SubredditController.php

    public function show(Subreddit $subreddit)
        {
    
            $posts = Subreddit::findOrFail(3)->posts()->get();
    
            return view('subreddit/show')->with('subreddit', $subreddit)
                                        ->with('posts', $posts);
        }

And this is Subreddit Model

    class Subreddit extends Model
    {
        protected $fillable = [
            'name',
            'description'
        ];
    
        public function user() {
            return $this->belongsTo('App\User');
        }
    
        public function posts() {
            return $this->hasMany('App\Post');
        }
    }

Also. am I doing this right? Is there a better way?

0 likes
3 replies
voxatik's avatar

I the link that triggers the show method you would have to pass the id of the category or other unique identifier to look up the category. You would have to set up the route with the id as well.

Get("subreddit/{id}", "SubredditController@show")

This should get you going.

ufodisko's avatar

I don't understand the need to add that route when I'm already using Route::resource('subreddit', 'SubredditController') Also when I visit subreddit/4 I get the posts of subreddit id 3 because that's what I'm telling it to findorfail.

ufodisko's avatar
ufodisko
OP
Best Answer
Level 10

I got it

I can access it with $subreddit->id

silly me

Please or to participate in this conversation.