Fetch latest post for each category or Parent Entity
HINDUSTAN shares a good tip about fetching latest post for each category in Laravel.
If you ever wanted to fetch latest posts for each category or parent entity, than please follow below code. Just a note: I have seen many people using “foreach” for category and running query. That is horrible thing to do. You will make a lot of query, and is not clean code. Just use 2 line below code for laravel and it will beat all your stress.
Let’s get to the Code.
Below code will get all “thread id” and “category id” in order of “created_at”
Laravel Fetch posts for each categoryPHP
// Laravel Eloquent Query $catList = Category::lists('id');
Now, It’s time to call all our latest thread.
Fetching latest posts from each category
// Laravel Eloquent Query $threads = Thread::wherein('category_id', $catList)->groupby('category_id')->latest()->get();
So, What’s Happening above.
Link:
This post is submitted by our members. Submit a new post.
Tags: Tutorials Laravel 5 v4.x Laravel 5.1 Laravel 5.2 Intermediate