Monday, March 6, 2017

Custom listing posts by category and nr. of posts

hope someone can give me idea of how i can accomplishe what im trying to do. Basically i need to list records from the database, more specically news posts, but i need to list the posts as groups of 6 by category alternately, where first post is the featured post.

I need to query by category, and after getting the posts from this category i need to group by 6 posts where first one is the featured (each post have a column that identifies what category or if feature is true or false.

So i imagine first creating in my Category model a method called posts:

public function posts(){
    return $this->hasMany('App\Post');
}

So than i n my controller, for example home page i can do like:

$categories = Category::all();

And than in my view blade i can do:

@foreach($categories as $category)
    @foreach ($category->posts() as $post)
        
    @endforeach 
@endforeach 

So now i need to group in each category in 6 posts where the first one is the featured post of this category. Final Result Schema:(ex: Total categories are 4 (A,B,C,D))

```
Category A
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category B
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category C
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category D
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category A
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category B
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category C
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

Category D
Feature Post | Normal Post | Normal Post | Normal Post | Normal Post | Normal Post

....

Can someone give a hint how i could do that?



via Pedro

Advertisement