Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

teambian's avatar

Find the last record based on a attribute of a table.

In laravel, I create a migration table named 'timelogs'. Assumed that, this table have three column id,userid,value. 'id' is primary key and have auto increment property , 'userid' is foreign key. I insert data 1,2,2,2,2 and 3,4,5,6,7 for'userid' and 'value' field respectively.

Now I want to find last inserted record.Such as userid = 2 and value = 7.Here userid field contain different user's id. I want to find specific user's last record. How can I do this without using primary key? Because if I use primary key then it will give the last record of that table. But I don't want that.

0 likes
7 replies
bestmomo's avatar

When you just create the record you can get the last one because you have the object. In other cases with created_at field it's easy but it's not in your table.

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

$last = Timelog::orderBy('id', 'desc')->first();
4 likes
teambian's avatar

Thank's a lot @bestmomo for give reply. Your reply works. But I want to find data based on 'userid' field. How can I do this?

Mort's avatar

@teambian, I would really advise adding a created_at timestamp field to your table.

bestmomo's avatar
$last_for_user = Timelog::where('user_id', $user_id)->orderBy('id', 'desc')->first();
2 likes
teambian's avatar
teambian
OP
Best Answer
Level 18

$last_record = DB::table('timelogs')->where('userid', $user_id)->orderBy('id', 'desc')->first();
//var_dump($last_record);

3 likes
wafer's avatar

DB::table('timelogs')->where('userid', $user_id)->orderBy('id', 'desc')->value("userid");

Please or to participate in this conversation.