26
votes

I have an Order and a Product models.
"Order" HasMany Product (and Product belongsTo Order)...

Let's say I want to display the 3 products of my order, how to do that ?
I know the first could be retrieved like $order->products->first()... but how to retrieve the second and third product?

I tried $order->products->find(1) but "1" represents the id of the product... which I don't want to know...

5

5 Answers

58
votes
$order->products()->skip(1)->first();//Second row
$order->products()->skip(2)->first();//Third row
....

Is more performant than loading all products and getting only first, second, ecc..


Instead if you want both second and third, you can get only them in a single query without load other rows, with similar approach:

$order->products()->skip(1)->take(2)->get(); //Skip first, take second and third
41
votes

I finally found the solution, this is the correct syntax:

 $order->products->get(0)->name;   will return the first record
 $order->products->get(1)->name;   will return the second record
 $order->products->get(2)->name;   will return the third record 

And so on...

4
votes
$order->products()->skip(1)->take(1)->first(); //Second row
$order->products()->skip(2)->take(1)->first(); //Third row

$order->products()->orderBy('salary','desc')->skip(1)->take(1)->first(); //Second highest salary row
$order->products()->orderBy('salary','desc')->skip(2)->take(1)->first(); //Third highest salary row
2
votes

Say you want a second product from Eloquent Collection

if you are sure that the array keys are same as array indexes, do that

$order->products->get(1)->name;

if you need the second item and you are not sure about the array keys, do this

$order->products->slice(1, 1)->first()->name;
1
votes

You can simply try this :

$order->products->take(3)->get();