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.

Also Read :  Convert Array to XML and XML to Array using PHP

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

Also Read :  PHP Domdocument Get selectors Class Tags Table img Elements

Example

Recommended For You.

Laravel 5.7 Queues Send Mail Tutorial With Example From Scratch
Today, We want to share with you Laravel 5.7 Queues Send Mail Tutorial With Example From Scratch.In this post we