A
A
A_Lincoln2018-03-22 15:24:08
Laravel
A_Lincoln, 2018-03-22 15:24:08

What is the correct way to pack records into an Eloquent collection?

There are two tables: categories and posts. The post is tied to its category (category_id).
The category model uses hasMany(Post::class). The Post model uses belongsTo(Category::class)
In a loop, I can access category->posts() and display posts from that category.
There was a task to pack posts back into categories.
For example, the input has a list of posts
Post1 category_id 1
Post2 category_id 1
Post3 category_id 1
Post4 category_id 4
Post5 category_id 7
and so on.
How to get a collection of three categories (id 1, 4, 7) at the output of these five posts, so that later in the cycle when calling category->posts() these posts are displayed each in its own category?
Can this be done using Eloquent itself?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question