7

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?

Sushila Singh
  • 215
  • 2
  • 3
  • 7

4 Answers4

11

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');
} 
Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
11

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();
Sohel0415
  • 9,523
  • 21
  • 30
5

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
Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54
-3

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)

patriziotomato
  • 591
  • 1
  • 11
  • 25
  • who is downvoting without any comment? – patriziotomato Feb 14 '18 at 05:33
  • Sure, I added the example just 1 minute afterwards. Immediate downvoting in this manner is worth thinking about! – patriziotomato Feb 14 '18 at 07:56
  • Background: I added this comment from my mobile first, then it took some seconds to paste the example. Now on my desktop I'm thinking about the friendly guys used the chance to downvote before I wanted to add even more details on my desktop. As I said, that's kind of impolite. – patriziotomato Feb 14 '18 at 08:01