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?
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?
latest()
:DB::table('tbl')->latest()->first(); // considers created_at field by default.
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');
}
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();
You can also use an Eloquent here for your query
TableModel::latest()->first(); // returns the latest inserted record
TableModel::oldest()->first(); // returns the first ever inserted record from your table
This is well documented here:
https://laravel.com/docs/5.6/eloquent#retrieving-single-models
You may also use the
count
,sum
,max
, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:
Examples:
$max = DB::table('tbl')::max('date');
$max = App\TblModel::where('active', 1)->max('date');
As described already, you do not necessarily need an Model for this using the DB::table
syntax.
What you should also may want to consider is the performance aspect of your provided answers here (in case you do not use an index on that column at least)