Как получить индекс элемента в коллекции? Мой код:
$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
if ($users->contains(Auth::id())){
//get the index of auth user id
}
Спасибо за помощь






Можно использовать коллекцию 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();
});
Просто будьте осторожны, потому что индекс может быть 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
}
$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
// this return a collection. So can do an if like this: $userIndex->count() > 0
$userIndex = $users->filter(function($user) {
return $user->id === Auth::id()
});