Laravel version:7.0
$posts = Post::where("status", 1)->get();
Above returns all approved posts.
$top_featured_posts = Post::where("status", 1)->orderBy("featured", "DESC")->take(4);
Above will get 4 posts order by featured.
$top_recent_posts = Post::where("status", 1)->latest()->take(4);
Above will get 4 posts order by created_at. ...
How can I get them with only one query?
I want to get results as following to use them.
$top_featured_posts[0], $top_featured_posts[1], $top_featured_posts[2], $top_featured_posts[3]
$top_recent_posts[0], $top_recent_posts[1], $top_recent_posts[2], $top_recent_posts[3]
Can anyone help me? Thank you
You need to try this:
$posts = Post::where("status", 1)->get();
$top_featured_posts = $posts->sortByDesc("featured", "DESC")->take(4)->values();
$top_recent_posts = $posts->sortByDesc("created_at")->take(4)->values();
Documentation Laravel Database: Query Builder
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.