I'm currently trying to access the index of a child in a HasMany relationship in a Laravel project. I have an order with many orderItems, but I can't seem to find a way to access the index of the orderItem I am dealing with from its relationship with the parent Order.
So, basically I want to be able to do $orderItem->order->index() if possible, is there anything within Eloquent that can give me this?
Here's some code to show you how I have the relationships setup...
Order.php
/**
* @return HasMany
*/
public function orderItems()
{
return $this->hasMany(OrderItem::class)->orderBy('id', 'DESC');
}
OrderItem.php
/**
* @return BelongsTo
*/
public function order()
{
return $this->belongsTo(Order::class);
}
What I want to do...
OrderItem::find(1)->order->index()
or something like that.
Any help is greatly appreciated.
If I get you correctly, You are trying to get all OrderItem
ids
related to Order
. Then You can use pluck() to get this-
$order = Order::find($orderId);
$ids = $order->orderItems()->pluck('id');
I apologise to everyone that I confused with the question, what I wanted was to get the index of the current OrderItem I am dealing with as if it had been loaded via a relationship call.
In the end, this is the code that worked for me...
$this->$order->orderItems->pluck('id')->search($this->id)
This then returned the correct index to me.