0

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.

2
  • Which version of Laravel are you using? Commented Jul 31, 2015 at 13:45
  • laravel 4.2 .......@lowerends Commented Jul 31, 2015 at 13:46

3 Answers 3

2

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

$product->get('subscription');
Sign up to request clarification or add additional context in comments.

1 Comment

No but in my code, I have an eloquent object being used as array and object, so I now have a custom array. I want it to behave like that too..so I don't have to replace my existing code.
0

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.

Comments

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

Example :

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

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

1 Comment

If you are not sure if something is a correct solution, please test it before posting it. That way you will have both learned something (whether it works or not, and ideally why it does so), and you will be able to pass it forward better. Ideally you will also be able to explain why it works and what was the problem in the original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.