如何从 Laravel 数据库查询数组中获取最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23635695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:30:44  来源:igfitidea点击:

How to get the last item from a Laravel database query array

phparrayslaravel

提问by Dan

Say I am querying the user table like this in Laravel:

假设我在 Laravel 中像这样查询用户表:

routes.php

路由文件

Route::get('/users', function()
{
    $users = DB::table('users')->get();
}

users.blade.php

用户.blade.php

<ul>
@foreach ($users as $user)
    <li>{{ $user->id }}</li>
@endforeach
</ul>

But I wanted the following with the last users id from the original query in the row below then how could I get that information?

但是我想要下面一行中原始查询中最后一个用户 ID 的内容,那么我怎么能得到这些信息呢?

users.blade.php

用户.blade.php

<ul>
@foreach ($users as $user)
    <li>{{ $user->id }}</li>
@endforeach
</ul>

<div id="last-user" data-user-id="{{ $users->lastUserId }}"></div>

回答by The Alpha

You may use lastto get the last item:

您可以使用last来获取最后一个项目:

$last = $users->last();