Prakhar Thakur
Prakhar Thakur

Reputation: 1229

Select second last record with Laravel - eloquent

How can i select the next to last record added to a table. I can select the last record like -

transition::order_by('created_at', 'desc')->first();

Upvotes: 12

Views: 16925

Answers (5)

samzna
samzna

Reputation: 435

or try this one

DB::table('transition')
  ->where('transition_id', '<=', $id)
  ->orderBy('transition_id', 'desc')
  ->skip(1)
  ->first();

Upvotes: 4

Mahedi Hasan
Mahedi Hasan

Reputation: 1068

Simply use this

\App\Transition::orderBy('created_at', 'desc')->skip(1)->first()

Upvotes: 2

fico7489
fico7489

Reputation: 8560

If you have auto increment ID field it is better to user that field, because created_at is very often same for more rows :

transition::orderBy('id', 'desc')->skip(1)->take(1)->get();

Upvotes: 3

Bilal Hamid
Bilal Hamid

Reputation: 11

second to last for unique column

DB::table('transition')->where('transition_id', '<=', $id)
->orderBy('transition_id', 'desc')
->skip(1)
->take(1)
->first();

Upvotes: 1

Try this:

transition::orderBy('created_at', 'desc')->skip(1)->take(1)->get();

Upvotes: 16

Related Questions