Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Item::oldest()->first() and Item::latest()->first(), this assumed you wanted it sorted by created_at, if you want another column, specify it as a paramter to the latest/oldest method.

http://laravel.com/api/5.1/Illuminate/Database/Query/Builder.html#method_latest

Last updated 9 years ago.
0

@tkprocat i will check on your reply. thanks, but earlier i got this from the laravel IRC. Model::order('field',desc/asc')->first() but i got this error "call to undefined function order()".

0

I know this is an old thread, but I thought for anyone finding this via Google (as I did), I would clean up the thread a little.

@tkprocat has a great solution and it works straight out the box! But the final reply is misleading and could throw a few people off. So here is an explanation of @ubilli's reply.

Model::order('field',desc/asc')->first();

This is incorrect and will throw all sorts of errors. However, it really isn't far from working.

Model::orderBy('field','asc')->first();

WHERE 'field' is your field name and 'asc' is interchangeable with 'desc' depending which order you need. Note that the function is orderBy() and not order().

As I said, it's really not a huge way off and I would still recommend the solution given by tkprocat but just in case you're down the rabbit hole with other issues, I hope I've cleared this up a little for you.

0

Hello

Outbound links are clickable links on your website that are When you just create the record you can get the last one because you have the object. In other cases with the created_at field, it's easy but it's not on your table.

Why dont you want to use primary key ? Because you can just do :

$last = Timelog::orderBy('id', 'desc')->first();

Hope it helps you

Last updated 6 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

ubilli ubilli Joined 10 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.