DEV Community 👩‍💻👨‍💻

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

Laravel 8 Get Latest Record From Database

In this article, we will see laravel 8 get the latest records from the database. In PHP, you can use order by clause with descending order to get the last record from the database but in laravel, you can simply get the last record using the laravel 8 eloquent model. Laravel provides the latest() method to get the last record from the database. In the MySQL database get the last record using the ORDER BY clause with desc.

So, let's see how to get the last record in laravel 8 or laravel 8 to get the last record SQL query.

Get Last Record Using MySQL:

You can get the last records using the below code example.

SELECT column_name FROM table_name  
ORDER BY column_name DESC  
LIMIT 1;
Enter fullscreen mode Exit fullscreen mode

Example:

select * from users ORDER BY id DESC LIMIT 1;
Enter fullscreen mode Exit fullscreen mode

Read Also: How To Generate QR Code In Laravel 8


Get Latest Records Using Laravel:

Example 1:

$user = DB::table('users')
                ->latest()
                ->first();
Enter fullscreen mode Exit fullscreen mode

Example 2 :

$user = User::orderBy('id', 'DESC')->first();
Enter fullscreen mode Exit fullscreen mode

Example 3:

$user = User::get()->latest();
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dimitri profile image
Dimitri Oliver

Good examples on how to do this ordering on data from a table. Just as side note, the third example will first get all the data from the table then it will order it in descending order.

You have to pay attention to the number of rows in the table in this case.

Tired of sifting through your feed?

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.