Laravel Collection Converts Array to Object

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

How to convert an array to object in PHP?

This one worked for me

  function array_to_obj($array, &$obj)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
$obj->$key = new stdClass();
array_to_obj($value, $obj->$key);
}
else
{
$obj->$key = $value;
}
}
return $obj;
}

function arrayToObject($array)
{
$object= new stdClass();
return array_to_obj($array,$object);
}

usage :

$myobject = arrayToObject($array);
print_r($myobject);

returns :

    [127] => stdClass Object
(
[status] => Have you ever created a really great looking website design
)

[128] => stdClass Object
(
[status] => Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
)

[129] => stdClass Object
(
[status] => The other day at work, I had some spare time
)

like usual you can loop it like:

foreach($myobject as $obj)
{
echo $obj->status;
}

Laravel collection converts array to object

The issue is that the filter() method does not rekey the underlying collection array. So, the Collection is still representing an array, it is just that your array looks like this:

[
4 => Object4,
7 => Object7,
]

While this is a perfectly valid array in PHP, this is not a proper array in JSON. Since this cannot be represented as an array in JSON, it is converted to an object in JSON.

In order to get this properly represented as an array in JSON, you just need to rekey the Collection array. The proper method for this is the values() method. All it does is call array_values on the underlying array. This will turn the above array in this:

[
0 => Object4,
1 => Object7,
]

Now, this is a proper numerically indexed array that JSON can understand and will treat as an array instead of an object.

While flatten may work for this particular case (your Collection is a collection of Eloquent Models), it is not actually the correct method, and may lead to unintended consequences. Additionally, it will perform a lot of extra logic that is not needed. Your best bet is to use the proper method for what you are trying to achieve, and that is the values() method.

$obj = Cars::with('brand')->orderBy('id')->get();

return $obj->filter(function($value, $key)
{
return $value->display == true;
})
->values();

Laravel - convert array into eloquent collection

Actually your $vouchers is an array of arrays,

So you may want to convert your sub-arrays to objects:

You can do it simply using:

foreach ($vouchers['vouchers'] as $key => $value) {
$vouchers['vouchers'][$key] = (object) $value;
}

.. or using collections:

$vouchers = collect($vouchers['vouchers'])->map(function ($voucher) {
return (object) $voucher;
});

Laravel collections documentation

How to covert Laravel's collection to array object collection?

Use toArray() which converts this object into an array.

$data->toArray();

Now the collection converted into an array and looks like:-

[
[
id: 1,
data1: 11,
data2: 12,
data3: 13,
created_at: null,
updated_at: null
],
[
id: 2,
data1: 14,
data2: 15,
data3: 16,
created_at: null,
updated_at: null
]
]

But as per your requirements, you don't want associative index for the array, So use

$data = array_values($data);

Now your keys has been removed and final data is:-

[
[
11,
12,
13
],
[
14,
15,
16
]
]

Convert Array To Collection in Laravel

Edit; I understand this question is getting a lot of hits based on the title so the TLDR for those people is to use the collect() helper to create a Collection instance. In answer to the questioner's brief:

If you have

$collection = collect([
(object) [
'website' => 'twitter',
'url' => 'twitter.com'
],
(object) [
'website' => 'google',
'url' => 'google.com'
]
]);

You then have your array wrapped in an instance of the Collection class.
That means it does not behave like a typical array (- it will be array-like, but don't treat it like it is one -) until you call all() or toArray() on it. To remove any added indices you need to use values().

$sorted = $collection->sortBy('website');

$sorted->values()->all();

The expected output:

[
{#769
+"website": "google",
+"url": "google.com",
},
{#762
+"website": "twitter",
+"url": "twitter.com",
},
]

See the docs https://laravel.com/docs/5.1/collections#available-methods

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays.

The all method returns the underlying array represented by the collection.

How to convert array and sub array to collection in Laravel?

You need a recursive call.

public static function convertToCollection()
{
$menu_list = self::menuList(self::$menu_list);
}

public static function menuList($list)
{
return collect($list)->map(function ($voucher) {
if(is_array($voucher)) {
return self::menuList($voucher)
}
return $voucher;
});
}

Laravel - Convert array back to a collection

You get Trying to get property of non-object because one of

DB::table('categories')->where('id', '=', $product->category_id)->first();

return null value.

You can fix it this way

$products = DB::table('products')->groupBy('category_id')->get();

$categories = collect();
foreach($products as $product){
$category = DB::table('categories')->where('id', '=', $product->category_id)->first();
if ($category) {
$categories->push($category);
}
}

If you want to get collection instance you must be use collect() helper method with array argument.
For example

collect($categories); // is_array(categories) is true

You are doing many request in foreach. That is not right way. Instead it you can achieve collection instance doing only 2 request.

 $categoryIds = DB::table('products')->pluck('category_id')->toArray();
$categories = DB::table('categories')->whereIn('id', $categoryIds)->get();

See docs https://laravel.com/docs/5.8/queries#retrieving-results



Related Topics



Leave a reply



Submit