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

baspa's avatar
Level 1

How to count duplicate relationships with Laravel Eloquent

I have the following tables Orders, Lamps and Lamp_Order which is a pivot table. The Lamp_Order table stores the id of an Order and a Lamp. An Order can contain multiple of the same Lamps. So it could be that there are for example 5 Lamps with an id of 1 connected to the same Order. I want to get the count of the same Lamps within an Order. So this method or function that I want to make should return 5 in this case.

I currently have this function in my OrderController to return the Order with the related Lamps:

public function index()
{
    $orders = Order::all();

    // Get the Lamps for each Order.
    foreach ($orders as $order) {
        $order->lamps;
    }

    return response()->json([
        'orders' => $orders
    ], 200);
}

The response in my vue front-end looks like this: enter image description here

As you can see there are some lamps with the same ID being returned. Instead I would like to return this Lamp with the count of how many times it is related to that Order.

My Order model looks like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email'
    ];

    /**
     * Get related Image.
     *
     * @return void
     */
    public function image()
    {
        return $this->hasOne(Image::class);
    }

    /**
     * Get related Lamps.
     *
     * @return void
     */
    public function lamps()
    {
        return $this->belongsToMany(Lamp::class)->withPivot('room');
    }

    public function countSameRelationships()
    {
    }

    /**
     * Detach related lamps when deleting Orders.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        static::deleting(function ($order) {
            $order->lamps()->detach();
        });
    }
}

I was thinking about creating a function in the Order model which I call in the index function in the OrderController. Can someone tell me if there is some sort of already existing function to count these "duplicate" relationships? Or what would be a good approach to tackle this problem? I prefer the solution to return the right data directly from the Laravel backend. But if it is also possible to apply some sort of filter function to remove and count duplicate relationships that would be fine as well.

0 likes
3 replies
baspa's avatar
Level 1

I don't want to count the total amount of relationships but I want to get the count per Lamp how many it occurs within an Order. So if an Order has 5 of the same Lamps it should return 5.

baspa's avatar
Level 1

Okay, at this moment I made the following solution in my Vue front-end as I didn't manage to solve the problem in my back-end:

  removeAndCountDuplicates(order) {
      // map to keep track of element
      // key : the properties of lamp (e.g name, fitting)
      // value : obj
      var map = new Map();

      // loop through each object in Order.
      order.forEach(data => {
        // loop through each properties in data.
          let currKey = JSON.stringify(data.name);
          let currValue = map.get(currKey);

          // if key exists, increment counter.
          if (currValue) {
            currValue.count += 1;
            map.set(currKey, currValue);
          } else {
            // otherwise, set new key with in new object.
            let newObj = {
              id: data.id,
              name: data.name,
              fitting: data.fitting,
              light_color_code: data.light_color_code,
              dimmability: data.dimmability,
              shape: data.shape,
              price: data.price,
              watt: data.watt,
              lumen: data.lumen,
              type: data.type,
              article_number: data.article_number,
              count: 1
            };
            map.set(currKey, newObj);
          }
      });

      // Make an array from map.
      const res = Array.from(map).map(e => e[1]);

      return res;
    },

This function increments a counter and adds it to the object. If someone has a solution that works in the back-end I would like to see that answer as well.

Please or to participate in this conversation.