laravel hasMany() relation, average item from collection

Posted 5 months ago by jaheller

Short "preview". Each order can have a feedback. In case the product is physical, the feedback can have many packaging_feedbacks.

The packaging_feedbacks are some kind of relation to the packaging_feedback_details.

Models are:


public function packagingFeedbacks()
    return $this->hasManyThrough('App\PackagingFeedbackDetail', 'App\PackagingFeedback',
        'feedback_id', 'id', 'id', 'user_selection');

id|type_id(used to group the "names" for each feedback option)|name


Now I would like to be able to get the average selection of the users for a physical product. I started by using:

    $result = Product::with('userFeedbacks.packagingFeedbacks')->where('id', 1)->first();

    $collection = collect();

    foreach ($result->userFeedbacks as $key) {

        foreach ($key->packagingFeedbacks as $skey) {

    foreach ($collection->groupBy('type_id') as $key) {

        echo ($key->average('type_id'));

This way returns float values, not the average user selection. Is there some better way, because I think it's not the cleverest way to do so.

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

Reply to

Use Markdown with GitHub-flavored code blocks.