is there a way to get all related data in laravel connection?

I have two tables named posts and categories. these two tables have one-to-many relationship and I wrote them in models like this:

class Post extends Model
    public function category()
        return $this->belongsTo(Category::class, 'category_id', 'id');
class Category extends Model

    public function posts()
        return $this->hasMany(Post::class, 'category_id', 'id');

This is work fine when I use $post = Post::find($id) in controller and retrieve one post and use $post->category to get category of this post. but what if I want to retrieve all posts and their categories together?
I mean, let’s assume that I have 10 posts in DataBase and I have $posts = Post::get(); to get all posts. now, how I can get categories of each post?
One way is loop! for example:

foreach($posts as $post) {
    $post['category'] = $post->category;

return response()->json($posts);

Yeah! I want to response in Json and I forgot to say earlier, sorry.

Is there better way to do this? I searched and I got nothing by my search. I’ll be appreciated if anyone response to my problem. 🙂


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The easiest way to include categories in each post model with json, is simply including it using with() and it will automatically transform it.

return Post::with('category')->get();

In Laravel you do not have to wrap models or collections in response->json(); it will automatically do that.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x