Posted inLaravel / Programming

How to get last record from table using PHP Laravel

How to get last record from table using PHP Laravel

In this tutorials,How to get last record from table using PHP Laravel I will display we two way to getting simple last row of the database table. In this simple example i going to use there are following method of 3 laravel eloquent for example here show you How to get last record of table in Laravel 5.

1)first()
2)orderBy()
3)latest()
Above simple three most method through we can simply select last record of any table of simple database.and we can use simple latest method to get last record from database table in simple Laravel application.

Get last record from table using simple orderBy clause

    $get_last_row=DB::table('products')->orderBy('id', 'DESC')->first();

Get last record from table datbase using latest method

I have simple “items” table using in database and i want just to get last record of “items” in records table. In first simple example i use latest() record with first() record because latest() record will fetch only simple latest record according to have new created_at then first() records will get each only single record:

	$get_last_row = DB::table('products')->latest()->first();

Using latest() belong to created_at field:

$get_last_row = DB::table('items')->latest()->first();

Using orderBy() belong to id field:

$get_last_row2 = DB::table('items')->orderBy('id', 'DESC')->first();

Using latest() belong to id field:

$get_last_row3 = DB::table('items')->latest('id')->first();

Laravel query latest record

public function users()
{
    return $this->belongsToMany(User::class, 'message')->orderBy('id', 'desc');
}

If we want to ste limit the total number of users simple returned, and other append ->take(10); like as 10 number to take only last 10 get users

Example

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype