簡體   English   中英

在 laravel-8 中獲取最后一個 id 表單數據庫

[英]get last id form database in laravel-8

我只想從我的數據庫中獲取最后插入的數據。 在這里,我從數據庫中獲取所有數據,但我只想要最后一個值。 這是 ProductController.php

function indextwo() 
{
    return DB::select("select * from  products");
}

這是 web.php

Route::get('products_link', [ProductController::class, 'indextwo']);

這是我目前的 output:

在此鏈接中,這是我插入的所有數據,但我只想要最后一個數據

您可以使用Query BuilderEloquent獲取最后一個 id。

查詢生成器

function indextwo() {
    return DB::table('products')->orderBy('id', 'DESC')->first();
}

Eloquent

function indextwo() {
    return Product::orderBy('id', 'DESC')->first();
}

也許你可以使用latest() function 來獲取

$user = DB::select("select * from  products")
            ->latest()
            ->first();

也許您可以直接在 controller 中使用 Model 名稱,就像您的 model 名稱是“產品”一樣,還可以使用 limit() 和 latest()

$user = Products::latest()->limit(1);

您可以遵循的一種非常簡單的方法

Product::query()->latest()->first() 

它將按照 id desc 的順序返回最新插入的數據。

另一種方式:

Product::query()->orderByDesc('id')->first();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM