Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent how to get the second or third record?

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

like image 920
nadir Avatar asked May 30 '15 21:05

nadir


People also ask

How can I get only one record in Laravel?

Using Laravel Eloquent you can get one row using first() method, it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

How do I get the latest updated record in Laravel?

cust_id') ->select('cust_info.id', DB::raw('MAX(cust_info. updated_at)')) ->orderBy('cust_info.id','DESC') ->first(); In the above query, I write select to get the id of last updated record.

How do I skip the first record in Laravel?

1 Answer. Show activity on this post. Laravel eloqunt provides nice way to achieve this. $users = User::orderBy('xp', 'DESC')->skip(50)->take(50)->get();


1 Answers

$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 
like image 92
Luca C. Avatar answered Sep 28 '22 08:09

Luca C.