1

I have an object of $person as below:

$person = Person::where('id', $id)->first();

According to which $person exists or not I load other data:

if($person) {
    $person->family_members = FamilyMemberController::FamilyMemberOf($person->id);
} else {
    $person->family_members = [];
}

In the view file, I check the $person->family_members if not empty and exists to add a generated value :

if(!empty(array_filter($person->family_members))) {
    // my code
}

But it throws an error:

array_filter(): Argument #1 ($array) must be of type array, Illuminate\Database\Eloquent\Collection given

I need to check this $person->family_members to make sure whether it's an array or a collection is not empty.

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36

6 Answers6

1

Use count method

if(count($person->family_members)>0){
    //your code
}
1

Writing code for if array do something if collection do something is the wrong way of implementation.

You can do two things.

  1. use both returns as collection()
  2. or either use both returns as an array[]

If collection

else {
    $person->family_members = collect();
}

If array

use ->toArray() at the end of Eloquent. Check this answer


As well, I think you are confused with array_filter(). Maybe you are searching for in_array() or contains()

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

We don't know your code, but given the error, it's safe to assume your method returns a Collection. You can see available methods in the docs. However, if you need it as array, all you need to do is call ->toArray() on the result Collection. Then you can use array_filter.

Yinci
  • 1,637
  • 1
  • 3
  • 14
0

What about just doing

if(!$person->family_members){
   // your code here
}

or

if($person->family_members){
   // your code here
} else {
   // code of "if it's empty" goes here
}
Daniel L
  • 329
  • 3
  • 13
0

You can use the count() function to return a count of an index. ex

if(count($person->family_members)){
    //do your true algo
}
Bevin NIno
  • 75
  • 7
0

Why you are using the empty method ?! Try this:

$person->family_members = $person ? FamilyMemberController::FamilyMemberOf($person->id) : null;
if($person->family_members){ // your code }

Try simple ways in Programming ;)

Ebrahim Bashirpour
  • 717
  • 2
  • 10
  • 21