0
votes

I want to display the post that is associated with a specific category.

I have a table for categories that are pre-defined, each associated with a unique id.

The I have a table for posts, I have a pivot table that links the two called category_post.

The pivot table consists of category_id & post_id.

I want to query the pivot table to bring back all the post_id associated with a particular category_id.

My Controller takes a parameter of the id of the selected category:

public function getCategoryPost($id)
    {


        $selectedID = DB::table('category_post')->select(['post_id'])->where('category_id', '=', $id)->get();
        $posts = Post::find($selectedID);

        return View::make('posts.category')->with('posts', $posts);

    }

Now I want to display the results in the blade but only the title of the post:

        @foreach($posts as $post)
        class="post-title"> {{$post->title}} 
        @endforeach   

This is what I have, and I get the following error "Object of class stdClass could not be converted to string"

Any suggestions?

1
$selectedID is an object. Post::find() turns it into a string. Just a guess. You should var_dump($selectedID);. - Sverri M. Olsen
$selectedId is an object, are you sure Post::find() takes objects, i dont thinks so. - anwerj

1 Answers

0
votes

First you should rebuild a bit your query Using Eloquent i suggest:

$selectedID = CategoryPost::where('category_id', '=', $id)
->select('post_id')
->first();

Since you are fetching ONLY ONE RESULT here you should use FIRST, not GET function as GET returns you an Array! If you insist using Get you should change your code to this:

 $posts = Post::find($selectedID[0]); // the first element of the response array

You should concider var_dump your results and queries before returning them to the view and see where the problem is! :) Regards and tell me if you need more help!