Home > Software design >  Laravel Checking if Array or Collection is not Empty to run
Laravel Checking if Array or Collection is not Empty to run

Time:09-14

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.

CodePudding user response:

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 don't think you are confused with array_filter(). Maybe you are searching for in_array() or contains()

CodePudding user response:

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.

CodePudding user response:

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
}

CodePudding user response:

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

if(count($person->family_members)){
    //do your true algo
}

CodePudding user response:

Use count method

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

CodePudding user response:

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 ;)

  • Related