Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data from the latest date in laravel?

In mySql, I can perform to data of latest date as follows:

select * from tbl where date = 'select max(date) from tbl';

But I don't know how to do this is laravel? How to do it?

like image 358
Sushila Singh Avatar asked Feb 14 '18 05:02

Sushila Singh


People also ask

How do I get the latest updated record in laravel?

cust_id') ->select('cust_info.id', DB::raw('MAX(cust_info. updated_at)')) ->orderBy('cust_info.id','DESC') ->first(); In the above query, I write select to get the id of last updated record.

How to get latest record in SQL by date?

From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table. Select * From SampleTable Order By [Date] Desc; After executing the above example, the server will return the records in such a way that the records with the latest dates appear at the top.

What is latest () in laravel?

latest() function in Laravel used to get latest records from database using default column created_at . latest() is the equivalent to orderBy('created_at', 'desc')

How to get the latest record using timestamp in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.


2 Answers

use orderbBy():

TblModel::orderBy('date','DESC')->first();

Or

DB::table('tbl')->orderBy('date', 'DESC')->first();

Update:

TblModel::where('date', TblModel::max('date'))->orderBy('date','desc')->get();
like image 154
Sohel0415 Avatar answered Dec 16 '22 13:12

Sohel0415


You can use latest():

DB::table('tbl')->latest()->first(); // considers created_at field by default.

Or

DB::table('items')->latest('date')->first(); //specify your own column

Under the hood:

latest() will orderBy with the column you provide in descending order where the default column will be created_at.

//Illuminate\Database\Query\Builder
public function latest($column = 'created_at')
{
    return $this->orderBy($column, 'desc');
} 
like image 20
Sapnesh Naik Avatar answered Dec 16 '22 12:12

Sapnesh Naik