Using Eloquent Model To Get Last Record
To get the last record using Laravel Eloquent you can call the model directly for example "Post" and then chain it with the "latest()" model. Other than that you can also get the whole collection and get the last item, and finally by ordering the post in descending order by ID then getting the first result.
<?php /* Directly Querying The Model */ Post::query() ->latest() ->first(); /* Getting Collection and Take Last Item*/ Post::all()->last(); /* Order the Post by Descending and get First Item */ Post::query() ->orderBy('id', 'desc') ->first();
Using Eloquent Model to Get Last Record ID
to get the last record ID you can directly chain the call "->id" property from the object instance itself.
<?php Post::query() ->latest() ->first() ->id; Post::all()->last()->id;
<?php /* get latest by the UUID */ Post::query() ->latest('uuid') ->first();
Using DB Facade to get Last Record in Laravel
If you do prefer more to use DB facade (fluent) then you can write your code as follows. You can make use of the "last()" method as well as the "latest()" method to get the last record.
<?php use \DB; /* Get the last post [which is essentially the last record]*/ DB::table('posts')->get()->last(); /* To access the property just chain the column */ DB::table('posts')->get()->last()->id; /* Another Approach */ DB::table('posts')->latest('published_at')->first();
Leave a reply