Laravel: How to get last N entries from DB

You can use the latest method on a query builder instance to get the last N entries from the database. Here's an example:

$lastNEntries = DB::table('table_name')->latest()->take(N)->get();

In this example, table_name should be replaced with the name of the table you want to query, and N should be replaced with the number of entries you want to retrieve.

Watch a course Learn object oriented PHP

You can also use the orderBy and limit method to get the last N entries

$lastNEntries = DB::table('table_name')->orderBy('id', 'desc')->limit(N)->get();

This orderBy method sorts the data in descending order based on the id and limit method limits the number of rows.

$lastNEntries = DB::table('table_name')->latest('created_at')->take(N)->get();

In this example, latest method sorts the data in descending order based on the created_at column.

Please note that this example uses the query builder, if you are using Eloquent, you can use the latest method on a model instance instead of the query builder.