1

I am retrieving users using many to many relationships. I want to loop through the user only one time that have two entries in pivot. e.g.

 $admin = Admin::first();
 $users = $admin->users;

 foreach($users as $user) {
 //Iterate through users that has different ids
 //Do not iterate over same user twice
}
Kamran Ali
  • 77
  • 3
  • 11
  • What stops you from doing an `if`-statement? If the id is not what you need, `continue` in the loop. – Manuel Mannhardt Nov 24 '17 at 07:52
  • As @ManuelMannhardt suggested, you can store the ids in an array that you looped through, and in each loop you can check if that id exist in the array. If exists -> skip, if not -> do the things you want to do. – Red fx Nov 24 '17 at 08:01
  • @REd fx2 can you give code example? – Kamran Ali Nov 24 '17 at 10:14
  • @KamranAli That was a general suggestion for object oriented programming, I do not practice php. But these sites may help you: https://stackoverflow.com/questions/14572313/in-php-how-can-i-add-an-object-element-to-an-array and https://stackoverflow.com/questions/37524969/check-if-an-object-exists-in-an-array – Red fx Nov 24 '17 at 13:41
  • @Red fx thank you for your help , actually what I need to show items one time that has duplicate entries in collection object.So it need some programming technique to count items of same ids and take one of them – Kamran Ali Nov 25 '17 at 04:35

3 Answers3

0

Nothing wrong with your code just use all() OR get() instead of first(). Or if you have multiple entries with single admin please share your model code

Maaz
  • 67
  • 5
0

If you dont need the duplicate user entries, it is also possible to avoid the duplicates in the $admin->users collection by using the distinct method:

$admin = Admin::first();
$users = $admin->users()->distinct()->get();

https://laravel.com/docs/5.5/queries#selects

Stefan Gi
  • 430
  • 4
  • 11
0

I found the solution myself. array_unique($array) was the solution. I pushed user ids to $users array and used array_unique($users).Thanks to php.net. Ref. http://php.net/manual/en/function.array-unique.php

 <?php
 $input = array(4, "4", "3", 4, 3, "3");
 $result = array_unique($input);
 var_dump($result);
 ?>
Kamran Ali
  • 77
  • 3
  • 11