LaravelTrainingWheels's avatar

Removing duplicates from Collection

I have a search controller which is doing the following:

LIKE query against Profile model to return profiles that match for one or more columns
LIKE query against Category model to return profiles that match for one or more categories
Any returned profile is pushed to a collection.

The problem I have is after collecting the profiles I have the results returned however there are duplicates if a profile matches for the Profile Model search as well as the Category Model search. I have tried numerous ways to remove these duplicates however I'm having no luck.

JSON Output for $collection:

Collection {#166 ▼
#items: array:5 [▼
0 => Profile {#191 ▶}
1 => Profile {#193 ▶}
2 => Profile {#192 ▶}
3 => Profile {#194 ▶}
4 => Profile {#196 ▶}
]
}

public function index(Request $request) {

  $query = $request->input('query');
  $keywords = preg_split('/\s+/', $query);
  $collection = new Collection;
  
  if(!$keywords) {
        return back()->with('info', 'You did not enter a search.');
  }
  else {
        $category = Category::with('profiles')->orWhere(function($c) use ($keywords) {
              foreach($keywords as $categoryValue) {
                    $c->orWhere('category', 'LIKE', "%".$categoryValue."%");
              }
        })->get();   
  
        $profile = Profile::where(function($p) use ($keywords) {
              foreach ($keywords as $profileValue) {
                    $p->orWhere('name', 'LIKE', '%' . $profileValue . '%')
                    ->orWhere('age', 'LIKE', '%' . $profileValue . '%')
                    ->orWhere('location', 'LIKE', '%' . $profileValue . '%')
                     ->orWhere('description', 'LIKE', '%' . $profileValue . '%');
              }
        })->get();
  }
  foreach($category as $cat) {
        foreach($cat->profiles as $catProfiles) {
              $collection->push($catProfiles);
        };
  };
  foreach($profile as $prof) {
        $collection->push($prof);
  }
  return view('searchresults', compact('query', 'collection'));
  }

Any help or advice you have would be greatly appreciated.

0 likes
5 replies
LaravelTrainingWheels's avatar

Thanks Zach,

I had tried this but must have been using it wrong after spending too long trying to get it right. Coming back to it after a break with the knowledge that I was trying the right method was what I needed to get it right.

If anyone is interested it was a really simple thing to get working:

$unique = $collection->unique('id'); $unique->values()->all();

This went in just before returning the view.

Shahrukh4's avatar

The short and easy way for doing this is as follows,

$arr = [
    'fruit' => 'Apple', 'fruit' => 'Mango', 'fruit' => 'Apple'
];

$collection = collect($arr);

$unique_data = $collection->unique()->values()->all(); 
2 likes

Please or to participate in this conversation.