How to get data from last date in laravel?

In mySql, I can execute the last date data as follows:

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

But I do not know how to do this, is it laravel? How to do it?

+4
source share
4 answers

use orderbBy():

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

Or

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

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 be orderBywith the column that you specify in the descendingorder where the default column will be created_at.

//Illuminate\Database\Query\Builder
public function latest($column = 'created_at')
{
    return $this->orderBy($column, 'desc');
} 
+2
source

Eloquent

TableModel::latest()->first(); // returns the latest inserted record

TableModel::oldest()->first(); // returns the first ever inserted record from your table
+1

:

https://laravel.com/docs/5.6/eloquent#retrieving-single-models

count, sum, max , . :

:

$max = DB::table('tbl')::max('date');
$max = App\TblModel::where('active', 1)->max('date');

As already mentioned, you do not necessarily need a model for this using the syntax DB::table.

What you should also consider is the performance aspect of your provided answers here (unless you are using at least the index in this column)

-3
source

Source: https://habr.com/ru/post/1693615/


All Articles