user3810794
user3810794

Reputation: 273

how to get latest record from the database having same id in laravel?

I am trying to to get latest record having the same id. For example I have table

 ID | Created_at
  1 |2016-04-26
  1 |2016-04-20
  1 |2016-04-18
  2 |2016-04-27
  2 |2016-04-19

I want to get result like this

ID  | Created_at
1   |2016-04-26
2   |2016-04-27

How do I do this in Laravel? I was only able to order the record by descending order. Don't know how to pick the latest record of each ID. Thank you.

Upvotes: 3

Views: 22026

Answers (6)

bipin patel
bipin patel

Reputation: 2111

You can try with whereRaw to getting last records in groupBy laravel

$data = Table::whereRaw('Created_at IN (select MAX(Created_at) FROM table GROUP BY ID)')->get();

Upvotes: 2

fcva
fcva

Reputation: 449

Include the directive Db

$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');

If you have user_id.

$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');

Upvotes: 1

user3810794
user3810794

Reputation: 273

Thank you everyone for help. I was able to solve this by

DB::raw("SELECT ID,created_at FROM <table name> a WHERE created_at=(SELECT max(created_at) FROM <table name> b WHERE a.ID=b.ID)

Upvotes: 2

Syiwa Wahyu Saputra
Syiwa Wahyu Saputra

Reputation: 121

Try using Collections service from laravel , and use last() method. Example:

$data = ModelName::all();
$last_data_object = collect($data)->last();

//try to see the object using var_dump()
var_dump($last_data_object);

I get it from https://laravel.com/docs/5.2/collections#method-last

Upvotes: 6

krunal nerikar
krunal nerikar

Reputation: 446

DB::raw('SELECT * FROM `test` WHERE 1 GROUP BY `ID` ORDER BY `Created_at` ASC');

Try this

Upvotes: 0

Kreshnik Hasanaj
Kreshnik Hasanaj

Reputation: 5005

Try it this way, it will give you the max grouped ID which will be the latest:

SELECT MAX(ID), Created_at
FROM table
GROUP BY ID, Created_at

Upvotes: 1

Related Questions