[英]get last id form database in laravel-8
I want to get only the last inserted data from my database.我只想从我的数据库中获取最后插入的数据。 Here, I get all data from the database but I want only the last value.
在这里,我从数据库中获取所有数据,但我只想要最后一个值。 This is ProductController.php
这是 ProductController.php
function indextwo()
{
return DB::select("select * from products");
}
This is web.php这是 web.php
Route::get('products_link', [ProductController::class, 'indextwo']);
Here is my current output:这是我目前的 output:
You can get the last id using Query Builder
and Eloquent
.您可以使用
Query Builder
和Eloquent
获取最后一个 id。
Query Builder查询生成器
function indextwo() {
return DB::table('products')->orderBy('id', 'DESC')->first();
}
Eloquent Eloquent
function indextwo() {
return Product::orderBy('id', 'DESC')->first();
}
Maybe you can use Model name direct in controller like your model name is "Product" and also use limit() and latest()也许您可以直接在 controller 中使用 Model 名称,就像您的 model 名称是“产品”一样,还可以使用 limit() 和 latest()
$user = Products::latest()->limit(1);
A very simple way you can follow您可以遵循的一种非常简单的方法
Product::query()->latest()->first()
It will return you the latest inserted data according to order by id desc.它将按照 id desc 的顺序返回最新插入的数据。
Another way:另一种方式:
Product::query()->orderByDesc('id')->first();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.