Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muzafferdede's avatar

How can i re-use Query Builder result to create multiple collections?

Hi,

I am trying to find a way to not write hardcoding to solve an issue.

I got this index method as:

    public function index()
    {
        $posts = Post::where('status','published')->paginate(4);

        $featured =  Post::where('featured',true)->get();

        return view('posts.list', compact('posts','featured'));
    }

As you can see i made 2 query on Post model just to get published and featured posts. I need to do like so because when i try to filter status and featured on same query, featured posts are going to be available only if current pagination has featured posts in the collection. So i am only able to see current pagination published featured posts.

I was thinking i could just do like so:

     public function index()
    {
        $posts = Post::all();

        $featured = $posts::where('featured',true)->get();

    $posts = $posts->paginate(4);

        return view('posts.list', compact('posts','featured'));
    }

I am trying to use same $posts query and just resign them to new variables and filter them. But doing like so caused original $posts variable to be changed during the process. So i end up with a $posts variable which contains only published and featured posts. But i need to list published only posts in one variable, published and featured only posts on another variable so i can loop through them in my view and list them in different section on the page.

Any suggestions?

I hope it is clear enough, Thank you for your help.

0 likes
3 replies
muzafferdede's avatar
muzafferdede
OP
Best Answer
Level 13

Just and update, I am able to use this way to make it work as i expected but i still believe there is a better way write this logic...

    public function index()
    {
        $posts = Post::where('status','published');

        $featured = $posts->get()->filter(function ($value, $key) {
            return $value->featured == true;
        });

        $posts = $posts->paginate(4);
        
        return view('posts.list', compact('posts','featured'));
    }
muzafferdede's avatar

@CRONIX - That didn't work. Pagination is still the issue. I am not sure if we are only able to paginate once it is in query builder stage. I am looking a way to paginate the collection after Post query builder result turn into a collection . That's what i am trying to figure out for now.

Please or to participate in this conversation.