Search code examples
phpmysqllaravelcollectionseloquent

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


Solution

  • 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
    }