I don't know if this is what you are looking for, but you can use the withCount method on your lamps relation, to get the number of lamps:
$order->withCount('lamps');
https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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:

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.
Please or to participate in this conversation.