1 month ago

How to create duplicate of a laravel collection

Posted 1 month ago by chesterBot

Hello guys, I have a laravel Collection with relations and there can be 2k-3k rows in relation, I m getting some rows from this relation to make some calculation and then delete rows so that next time I have to query from fewer rows than the previous, But when loop complete relation becomes empty,

    public function getResult($tournament_id, $date)
        $tournament = (new WebsiteService())->getTournamentResultByDate($tournament_id, $date);
        $sortedResultAndPlayers = (new WebsiteService())->getSortedResultByDate($tournament, $date);
        $tournament = (new WebsiteService())->getTournamentResultByDate($tournament_id, $date);

        return view('website.index', compact('tournament', 'date', 'sortedResultAndPlayers'));

I m calling $tournament = (new WebsiteService())->getTournamentResultByDate($tournament_id, $date); twice because insidegetSortedResultByDate() $tournament->tournamentResult becomes null because of using forget(),rows in tournamentResult are equal to playerstruns. And there can be 150 player and 11-20 turns.wrost scnario 15020. it can be more wrost.

    public function getSortedResultByDate($tournament, $resultDate)
        $result = [];
        foreach ($tournament->players as $player) {
            $playerResult = $tournament->tournamentResult->where('player_id', $player->id)->where('date', $resultDate);
            foreach ($playerResult as $key => $value) {
            $result[$player->id] = $playerResult->sum("total_runs");
        return $result;

can you please also help me ? also if there is another way to optimize ?

Please sign in or create an account to participate in this conversation.