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...
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.
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.
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();
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With