如何获取Laravel集合中的元素索引

use*_*349 2 php mysql collections laravel eloquent

如何检索集合中元素的索引?我的代码:

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

if($users->contains(Auth::id())){
    //get the index of auth user id
 }
Run Code Online (Sandbox Code Playgroud)

感谢帮助

new*_*e02 5

您可以使用收集search()方法:https : //laravel.com/docs/5.7/collections#method-search

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

$userIndex = $users->search(function($user) {
    return $user->id === Auth::id();
});
Run Code Online (Sandbox Code Playgroud)

请注意,因为索引可能为0:

// DON'T do this
if($userIndex) {
    // this will get skipped if the user is the first one in the collection
}

// Do this instead
if($userIndex !== false) {
    // this will work
}
Run Code Online (Sandbox Code Playgroud)