0

How can I get the array from a object? I'm trying to get to the empty array so that I can validate on it's empty state.

$object = Illuminate\Database\Eloquent\Collection Object;

print_r($object);

if(empty($object->array)){

}

output

Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
        )

)
melkawakibi
  • 823
  • 2
  • 11
  • 26
  • 1
    you can typecast it, like (array)$array – Bhavya Shaktawat Jul 27 '17 at 09:16
  • @melkawakibi look here https://stackoverflow.com/a/4345609/2520628 – Tejashwi Kalp Taru Jul 27 '17 at 09:17
  • I change the code, now it's an Eloquent Object which has an Array inside – melkawakibi Jul 27 '17 at 09:17
  • 1
    Have you tried the different ways described by Gary Green here https://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty ? – Kenjin Jul 27 '17 at 09:21
  • 1
    @melkawakibi - It's a ___protected___ property of the object.... that means it isn't directly accessible from outside the object.... Why don't you just use the object methods to access the data, rather than trying to break OOP – Mark Baker Jul 27 '17 at 09:26
  • I just figured that out. It's of the type Collection which I didn't notice. Using the method Collection::isNotEmpty() is the solution. – melkawakibi Jul 27 '17 at 09:29

2 Answers2

2

The object is of the type Eloquent\Collection which means that it has access to a set of methods.

Eloquent\Collection | available methods

Collection provides a set of methods to validate the state of an array inside the Object. Two of which are interesting in the case described by me (OP):

  • IsEmpty
  • IsNotEmpty

Implementation

$website = $this->websitedb->findOneByUrl($this->url);

if($website->isNotEmpty()){

    $uniqueId = rand() . $website[0]->id;

    //save scan to database
    $this->scan = $this->scandb->create($website[0]->id, $uniqueId);

    $this->scandb->createModule($this->scan->id, $options);

}
melkawakibi
  • 823
  • 2
  • 11
  • 26
0

Try like this:

if ($object->array === array()) {
    echo 'this is explicitly an empty array!';
}
Anand Pandey
  • 2,025
  • 3
  • 20
  • 39