How to get last seven record from db in laravel

Viewed 80
     
$posts=head::select('DATE','fno')->limit('7')->get();

I used this code but it returns first 7 record i want to return last seven inserted record

4 Answers

Try this query:

$posts=head::select('DATE','fno')->latest('DATE')->take(7)->get();

if Date column is inserted date time.you can do this

$posts = head::select('DATE','fno')->orderBy('DATE','desc')->limit(7)->get()

in your code,you don't get the last record becuase sql limit if start from above.so we order by something reverse.here we reverse DATE

Based on the documentation, oldest order your query by date. By default, the result will be ordered by the table's created_at column. If you want to change the column that it reference, put the column name inside the oldest syntax. Like so, ...->oldest("column_name")->...

$posts=head::select('DATE','fno')->oldest()->limit(7)->get();

Change the date format accordingly. It will work.

$posts = head::select(DB::raw("DATE_FORMAT(DATE,'%Y-%m-%d')", 'fno')->take(7)->get();
Related