How to retrieve data from the latest date in laravel?
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 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');
}
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