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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With