hondnl's avatar

Laravel Collection to Object

Is it possible to return an object from a laravel collection ?


$originalArr =[
    'foo' =>'bar',
   'foo2' => 'bar2'
    
]

$coll=collect($originalArr)->reject(function($item){

    // do something
});


$arr = $coll->toArray();

// array
dump($arr)

// but what if I want to have an object ?
$object  = (object) $arr;

dump ($object) 


//So you can access the attributes like  $object->foo.

But this seems fairly stupid... First make a collection , then convert to an array and then once again convert to an object.

Is there a more efficient way?

0 likes
6 replies
JeffH's avatar

You could do

$coll->toJson();

Maybe thats what you're looking for?

1 like
deepu07's avatar

@hondnl Loop array and convert in looping from array to object i.e. $collection->first();

azurinspire's avatar
$originalArr =[
    'foo' =>'bar',
   'foo2' => 'bar2'   
]

$coll=(object)collect($originalArr)->reject(function($item){
    // do something
})->all();

echo $coll->foo;
3 likes
Snapey's avatar

Think of Collection as a super array. It can hold an array of things, be they strings, arrays or objects

You have created a collection of strings.

Not really sure what you are wanting to do?

Perhaps you need to create a class which uses a collection internally to store its members?

Cronix's avatar

Collections are basically an extension to the php native array. It's meant to work with arrays. The arrays can certainly contain objects, such as eloquent results, but at the core it's an array. So maybe you're using the wrong tool for the job here? It might be helpful to describe what you actually want to accomplish, rather than how you're currently trying to do it. Yes, it does look crazy doing it the way you are with your fake data, but what are you really trying to do?

1 like
tykus's avatar

You don't need a Collection at all:

$originalArr =[
    'foo' =>'bar',
   'foo2' => 'bar2'   
]

(object) array_filter($originalArr, function ($element) {
    // test to NOT reject element
});

Please or to participate in this conversation.