Search Value in Laravel Collection

I have a collection which contain user contacts, I want to search a value in this collection.

I tried $itemCollection->where('username', $search); but it`s showing me only if $search value is fully equal to username but I want to get results which has contains that value too.

For example I have "yunus" value as an username and when I`m searching "yunus" it is working well but I want to see result if I search "yun" or "y" values too.

I searched it and I did found I must to use where 'like' method but I did discovered it is not working for collections :(

My function for get user contacts which has my searched username value

public function index(Request $request)
    {

      $contacts = [];
      $user = request()->user();
      $search = $request->search;

      Contact::for($user->id)
      ->orderBy('created_at', 'DESC')
      ->get()
      ->each(function ($contact) use ($user, &$contacts) {
          $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
          $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
      });

      $itemCollection = collect($contacts);

      $filtered = $itemCollection->where('username', $search);


      $filtered->all();


        return response()->json($filtered);
    }

Result : Json output

Upvotes: 3

Views: 18278

Answers (1)

Peter
Peter

Reputation: 1725

Try using filter() instead of where():

$itemCollection = collect($contacts);
$filtered = $itemCollection->filter(function($item) use ($search) {
    return stripos($item['username'],$search) !== false;
});

https://laravel.com/docs/5.7/collections#method-filter

Upvotes: 7

Related Questions