jmadlena's avatar

Convert JSON to Eloquent Collection

I am working with the MailChimp API to get a list's merge variables (inputs a subscriber needs to fill out to subscribe to an email newsletter). Rather than having a table dedicated to merge vars, I've opted to serialize them, store them in the database, then unserialize and loop through them in the needed function. I would like to stick with standard Laravel loops like @foreach. However, when I attempt to do so, I get a 'Trying to get property of non-object' (aka it's not an Eloquent collection).

Is there a way to take a JSON array an store it in such a way that allows me to loop through it with @foreach? I see that you can convert an Eloquent collection to JSON, but can't find the reverse function.

0 likes
7 replies
socks's avatar

Not sure I completely understand what you're doing, but new \Illuminate\Support\Collection(json_decode($json, true)) will create a Collection with your JSON string.

2 likes
JarekTkaczyk's avatar
Level 53

@jmadlena

@socks gave you the answer, however if all you need is a foreach loop, then you don't need the collection at all. Just

$array = json_decode($json, true);
8 likes
baumgars's avatar

@JarekTkaczyk somehow i get back something like { ... [{ instead of { ... {{ The latter is how Laravel collect() returns an array of arrays (needing it in a Livewire view).

jmadlena's avatar

I think I was a bit exhausted when I wrote the original post, haha. I assumed that the @foreach loop needed a collection, but it just needs a PHP array. I will use json_decode to convert the JSON object to an array I can loop through.

Thanks for your help!

oburatongoi's avatar
// convert json to array
$array = json_decode($json, true);
//  create a new collection instance from the array
collect($array);
4 likes
Zugor's avatar

Working sample.

$collection = collect(json_decode($json_here, true));
$data = $collection->where('id', 1)->data;
5 likes

Please or to participate in this conversation.