Last Updated:

Laravel: how to get the last record from a table

This is an article in the Laravel chip series. And in this article, we'll look at how to quickly retrieve the last record from a table using Eloquent. Yes, you can get all the values then sort by the date of addition. But there is a simpler way, or rather the same way, but to use a special model method. It's Laravel, after all.

And so we have a table of data.

last record from a table 1

And we want to get the last record from the table. I will use the example from the last article "Laravel: how to copy a row from a table using Eloquent".

We have an OrderController controller to add the last method to it

    public function last()
    {
        $order = \App\Order::latest()->first();

        return view('last',['order' => $order]);
    }

The latest() method sorts our records by the created_at field.

Now let's create a route

    Route::get('last', 'OrderController@last')->name('last');

And let's create a last.blade pack.php

<!DOCTYPE html>
<html lang="en">
<head>
    <metacharset="UTF-8">
    <title>Last line output</title>
    <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
    <style type="text/css">
        table, th, td{
            border: 1px solid;
            padding: 5px
        }
    </style>
</head>
<body>
    <div class="container">
        <table>
            <head>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Date created</th>
                    <th>Update date</th>
                    <th></th>
                </tr>
            </thing>
            <tr>
                <td>{{ $order->id }}</td>
                <td>{{ $order->name }}</td>
                <td>{{ $order->created_at }}</td>
                <td>{{ $order->updated_at }}</td>
                <td><a href="{{ route('copy',['id' => $order->id])}}" class="btn btn-default">Copy</a></td>
            </tr>
        </table>
    </div>
</body>
</html>

We can check everything. Go to test.loc/last and see:

last record from a table 2

As you can see, it's simple.

Conclusion.

We have derived the last record from the table using the Eloquent – latest() method, which sorts the records by the created_at field. And the most interesting thing is that we can use this method in relationships.