12

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

Simpledev
  • 598
  • 1
  • 11
  • 22

3 Answers3

28

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
}
newUserName02
  • 1,598
  • 12
  • 17
  • This is not working if the collection was sorted (after initialization). The doc states the it will return the 'key' of the item. While the index(position in list) might be different. – DoruChidean Sep 01 '23 at 08:25
0

In model class:

protected $appends = ['row'];

public function getRowAttribute()
{
    return $this->where('id', '<', $this->id)->count();
}

In php code:

$row = $model_name->row;
ugexe
  • 5,297
  • 1
  • 28
  • 49
-1
$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()
});