3

I have problem to get value of protected array in my laravel project and want to save my data into database using foreach. I used to print_r my data

print_r($request->data);

Here is my array data:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 900
                    [zone_id] => 1
                    [account_id] => 2
                    [size] => 23474836488
                )

            [1] => stdClass Object
                (
                    [id] => 9001
                    [zone_id] => 2
                    [account_id] => 2
                    [size] => 23474836488
                )
        )
)

Is there any solution of my problem?

2
  • 1
    Convert it to array first print_r($request->data->toArray()). Commented Jul 17, 2020 at 10:28
  • 3
    Would you be better off just looping over the collection - stackoverflow.com/questions/48126573/…. Commented Jul 17, 2020 at 10:29

1 Answer 1

1

You are getting an array in the object.

You can access it as below.

foreach($request->data as $data){
    echo $data->id;
    echo $data->zone_id;
    echo $data->account_id;
    echo $data->size;
}

In Laravel, whenever you'll execute DB query or fetch records from database it will return you this kind of object.

If you want to see the object to array the as per @Ammar Faizi Comment you can convert it into array. $request->data->toArray();

Sign up to request clarification or add additional context in comments.

2 Comments

Please do explain that Collection supports any array operator due to the fact that it implements ArrayAccess and Enumerable. This doesn't happen by magic.
I am getting Call to undefined method Symfony\Component\HttpFoundation\ParameterBag::toArray() @Dilip

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.