Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of element in Laravel collection

How to retrieve the index of an element in a collection ? My code :

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

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

Thank's for help

like image 899
user2916349 Avatar asked Dec 07 '18 01:12

user2916349


1 Answers

You can use the collection search() method: 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();
});

Just be careful, because the index might be 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
}
like image 52
newUserName02 Avatar answered Nov 08 '22 05:11

newUserName02