We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

How to properly use ->filter so it returns as object on resultset

Hi!

First time I use ->filter, so I'm probably doing something wrong. I want a resultset where only those with a specific ID is given.

I have simply:

$all_statuses = Statuses::findAll();
var_dump(count($all_statuses)); // 84 statuses given
$all_statuses->getFirst();

Works perfectly.

This doesn't work:

$all_statuses = Statuses::findAll();

$filtered = $all_statuses->filter(function($Statuses){
    if ($Statuses->privacy == 5) {
        return $Statuses;
    }
});
var_dump(count($filtered)); // 31 statuses given
$filtered->getFirst(); // Gives error

Gives:

Fatal error: Call to a member function getFirst() on a non-object

My paginator won't work because it's a non-object. Not sure what to do here.

Thank you!



4.7k
Accepted
answer

Hi there :)

First- there is no findAll method available.

For the issue- it is normal, because $filtered it is just and array. So... u can use just $filtered[0] to get the fisrt or array_shift

Good luck :)