CoderTn
CoderTn

Reputation: 997

Filter a collection in Laravel

i want to filter a collection in order to return only items with fullname that is like the one given in parmaters


   public function searchFriend($fullName){
        return Auth::user()->friends->filter(function ($item) use ($fullName) {
             return false !== stristr($item->friend->full_name, $fullName);
        });
    }

the function actually is not returning the correct results.

Upvotes: 0

Views: 266

Answers (2)

MichalOravec
MichalOravec

Reputation: 1708

I guess friend is a relationship to the User model so it could be

public function searchFriend($fullName) 
{
    return Auth::user()->friends()->whereHas('friend', function ($query) use ($fullName) {
        $query->where('full_name', 'like', "%{$fullName}%");
    })->get();
}

If you have first_name and last_name in User model then you can use concat.

public function searchFriend($fullName)
{
    return Auth::user()->friends()->whereHas('friend', function ($query) use ($fullName) {
        $query->whereRaw("concat(first_name, ' ', last_name) like ?", ["%{$fullName}%"]);
    })->get();
}

Upvotes: 1

Qirel
Qirel

Reputation: 26450

Instead of accessing the collection directly, you can do the filtering in SQL.

public function searchFriend($fullName){
    return Auth::user()
        ->friends()
        ->where('full_name', 'like', '%'.$fullName.'%')
        ->get();
}

If you, for whichever reason, need to do it on the collection, then the problem with your current code is that $item represents the friend, so you're checking $item->friend->full_name instead of $item->full_name.

public function searchFriend($fullName){
    return Auth::user()
        ->friends
        ->filter(function ($item) use ($fullName) {
             return false !== stristr($item->full_name, $fullName);
        });
}

Upvotes: 1

Related Questions