There are many cases where we need to get only last record of table in our project. We can retrieve the latest record of a table using latest() or orderBy()
Here are several ways to achieve the result depends on what you choose to use for database persistence.
$user = DB::table('users')->latest()->first();
$user = DB::table('users')->orderBy('id', 'DESC')->first();
$user = User::latest()->first();
$user = User::select('id')->where('username', $username)->latest('id')->first();
$user = User::orderBy('created_at', 'desc')->first();
$user = User::all()->last();
$username = User::all()->last()->pluck('username');
$latest_id = User::all()->last()->id;
$latest_id = User::orderBy('id', 'desc')->first()->id;
Don’t use all()
method if your table has lots of data.