user2929209
user2929209

Reputation:

Laravel returning users last item from the database

Im trying to return a single instance of Sheetentry. More specifically the last one the user submitted. I know i'm not far off just not quite used to the framework yet.

Any feedback is appreciated.

return Sheetentry::where('user_id', $user->id)
  ->limit(0)->offset(0)
  ->orderBy('created_at', 'asc')
  ->get();

Upvotes: 1

Views: 43

Answers (2)

cbcaio
cbcaio

Reputation: 464

Could you be more specific when you say "submitted" ? I mean, submitted to create, update, or what?

I'm asking this because if you only care about the last created SheetEntry, you can use your field created_at as like @RiggsFolly mentioned ( if it doesn't work use first() instead of get() ) otherwise you can check updated_at, or maybe both depending on your needs.

It would be easier to help you if we knew exactly what you want.

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94672

If you want the last entered row then try sorting descending, so you get the oldest row first in the result set. Then just limit to 1 not 0. And I am fairly sure you then do not need the offset() at all.

return Sheetentry::where('user_id', $user->id)
                   ->orderBy('created_at', 'desc')
                   ->limit(1)
                   ->get();

Upvotes: 3

Related Questions