Ali Gajani
Ali Gajani

Reputation: 15091

How to use a Laravel Collection as both object and array?

I am doing this:

$product = new \Illuminate\Database\Eloquent\Collection($product_array);

But it works as an array not as an object like $product->subscription won't work, but $product['subscription'] would work.

Upvotes: 0

Views: 1087

Answers (3)

Sakal
Sakal

Reputation: 1

$product = (object) $product_array;
$product->subscription; 

Example :

$product_arr = [ 
   'name' => 'bag',
   'qty' => 4,
];

$product = (object) $product_arr;
$product->name; // result = bag

Upvotes: 0

Justin Reasoner
Justin Reasoner

Reputation: 144

You can use ArrayObject with the ArrayObject::ARRAY_AS_PROPS flag to

$api = new \ArrayObject(collect([
   'api_version' => 1,
   'facebook_id' => 1,
]),2)

echo $api->facebook_id; // ouputs 1

Notice the 2 is just shorthand for ArrayObject::ARRAY_AS_PROPS to mask the uglyness.

There must be another way and we're just missing something. I'm on Laravel 5.4 and trying to use this in a method to take either $request or something like $api from the example.

Upvotes: 0

lowerends
lowerends

Reputation: 5267

You can use collections like this in an object-oriented way:

$product->get('subscription');

Upvotes: 2

Related Questions