Have you tried using the collection unique() method? https://laravel.com/docs/master/collections#method-unique
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.
Please or to participate in this conversation.