Plotting a graph of survey answers in Laravel I'm using PHP (Laravel) to iterate over the survey_answers table and build datasets which I can show in a graph. I'm just wondering if this is the way to go.

ChartFactory.php

public static function buildFromSurvey($survey)
{
    $chart = new Chart($survey-&gt;name);

    foreach($survey-&gt;answers as $answer) {

        if($chart-&gt;hasDataset($answer-&gt;user_id)) {
            $dataset = $chart-&gt;getDataset($answer-&gt;user_id);
        } else {
            $dataset = new Dataset();
            $dataset-&gt;setTitle($answer-&gt;user-&gt;name);
            $dataset-&gt;setColor(config('assessment.chart_colors_survey')[0]);
            $dataset-&gt;setOwner($answer-&gt;user);
            $chart-&gt;addDataSet($dataset);
        }

        // Create the category if not exists in this dataset
        if ($dataset-&gt;hasDataItem($answer-&gt;question-&gt;category-&gt;name)) {
            $category = $dataset-&gt;getDataItem($answer-&gt;question-&gt;category-&gt;name);
            $category-&gt;addScore($answer-&gt;score);
        } else {
            $category = new Category();
            $category-&gt;setName($answer-&gt;question-&gt;category-&gt;name);
            $category-&gt;addScore($answer-&gt;score);

            $dataset-&gt;addDataItem($category);
            $chart-&gt;addLabel($answer-&gt;question-&gt;category-&gt;name);
        }
    }

    return $chart;
}
I think my main criticism of this code would be that it is asymmetric in terms of where ownership of instantiating your different object dependencies lives.

For example, in the first conditional around whether Dataset exists on the Chart, why does this code need to own the logic to create and attach a new Dataset?  If the Chart object "owns" the datasets, I would think that perhaps all this code would do is call a Chart::createNewDataset() or similar method to handle the work building a new dataset and setting it on the Chart.

This same concern exists for me with regards to creating Category objects.

I would also strongly recommend using type hinting for the parameter to enforce that you are getting passed a valid survey object.