Reputation: 2469
Question: Why do the old approach returns the right value see result old approach and the new HOM approach returns the whole collection?
Role Model
class Role extends Model {
public function getName() {
return $this->name;
}
}
Controller
$roles = Role::all(); // get all roles to test
// old approach
$roles->each(function(Role $i) {
var_dump($i->getName());
});
// new approach (HOM)
var_dump($roles->each->getName());
If I implement the new approach with higher order messaging it returns me the whole Collection, if I use the old one I get the right result.
Result old approach
string(11) "Application"
string(6) "System"
string(7) "Network"
string(7) "Manager"
Result new approach
object(Illuminate\Database\Eloquent\Collection)#196 (1) {
["items":protected]=>
array(4) {
[0]=>
object(App\Modules\Role\Role)#197 (24) {
["connection":protected]=>
NULL
["table":protected]=>
NULL
["primaryKey":protected]=>
string(2) "id"
["keyType":protected]=>
string(3) "int"
["incrementing"]=>
bool(true)
["with":protected]=>
array(0) {
}
["perPage":protected]=>
int(15)
["exists"]=>
bool(true)
["wasRecentlyCreated"]=>
bool(false)
["attributes":protected]=>
array(5) {
["id"]=>
int(1)
["name"]=>
string(11) "Application"
["description"]=>
string(91) "Voluptatem similique pariatur iure. Et quaerat possimus laborum non sint aspernatur fugiat."
["created_at"]=>
string(19) "2017-03-03 11:56:09"
["updated_at"]=>
string(19) "2017-03-03 11:56:09"
}
["original":protected]=>
array(5) {
["id"]=>
int(1)
["name"]=>
string(11) "Application"
["description"]=>
string(91) "Voluptatem similique pariatur iure. Et quaerat possimus laborum non sint aspernatur fugiat."
["created_at"]=>
string(19) "2017-03-03 11:56:09"
["updated_at"]=>
string(19) "2017-03-03 11:56:09"
}
["casts":protected]=>
array(0) {
}
["dates":protected]=>
array(0) {
}
["dateFormat":protected]=>
NULL
["appends":protected]=>
array(0) {
}
["events":protected]=>
array(0) {
}
["observables":protected]=>
array(0) {
}
["relations":protected]=>
array(0) {
}
["touches":protected]=>
array(0) {
}
["timestamps"]=>
bool(true)
["hidden":protected]=>
array(0) {
}
["visible":protected]=>
array(0) {
}
["fillable":protected]=>
array(0) {
}
["guarded":protected]=>
array(1) {
[0]=>
string(1) "*"
}
}
}
Upvotes: 1
Views: 390
Reputation: 35190
each
just iterates over the collection, it doesn't actually return anything. If you want it to return the value of getName()
for each iteration then you could use map e.g.
dump($roles->map->getName());
Hope this helps!
Upvotes: 3