38

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...

kupendra
  • 1,002
  • 1
  • 15
  • 37
nadir
  • 1,223
  • 4
  • 12
  • 21

5 Answers5

74
$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
Luca C.
  • 11,714
  • 1
  • 86
  • 77
46

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...

kirgy
  • 1,567
  • 6
  • 23
  • 39
nadir
  • 1,223
  • 4
  • 12
  • 21
8
$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
snieguu
  • 2,073
  • 2
  • 20
  • 39
Anas
  • 81
  • 1
  • 1
2

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;
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
1

You can simply try this :

$order->products->take(3)->get();
kupendra
  • 1,002
  • 1
  • 15
  • 37
  • For example, if I need the product name, I tried $order->products->take(3)->get('name'); (I get a null result), then I tried $order->products->take(3)->get()->name; (I get an error "missing argument") – nadir May 31 '15 at 08:26
  • Try this `$order->products->take(3)->select('name')->get()` – kupendra May 31 '15 at 08:46
  • Still does not work: "Call to undefined method Illuminate\Database\Eloquent\Collection::select()" – nadir May 31 '15 at 23:20
  • maybe try $order->products()->take(3)->get(); – Kenny Ong Feb 05 '18 at 20:26