0

I have a MongoDB collection set up with multiple embedded documents. This is how my sample document looks like:

{
    "_id" : ObjectId("58a331ffb854d000f97862f3"),
    "first_name" : "John",
    "last_name" : "Doe",
    "email" : "test@test.com",
    "password" : "$2y$10$fIuECeTqvSUY1g.VPgWxceEzB0/q2OtgDXlm9ZTqwY77U74hVEe6q",
    "updated_at" : ISODate("2017-02-14T16:36:15.079Z"),
    "created_at" : ISODate("2017-02-14T16:36:15.079Z"),
    "diagnosis" : [ 
        {
            "d_name" : "Asthma",
            "d_isTreated" : "No",
            "d_diagnosed_at" : "2017-02-14"
        }, 
        {
            "d_name" : "Bronchitis",
            "d_isTreated" : "No",
            "d_diagnosed_at" : "2017-02-14"
        }, 
        {
            "d_name" : "Hepatitis C",
            "d_isTreated" : "No",
            "d_diagnosed_at" : "2017-02-14"
        }
    ]
}

The parent document belongs to User class. However, when in my home page view I try to retrieve a list of diagnosis for each user like this:

<center>
    @foreach($users as $user)
        {{ $user->diagnosis }}
    @endforeach
</center>

Laravel is unable to retrieve the array of diagnosis objects and outputs an error:

ErrorException in helpers.php line 532:
htmlspecialchars() expects parameter 1 to be string, array given (View: /Users/janisozolins/Sites/patientapp/resources/views/home.blade.php)

How can I retrieve these arrays? I'm also planning to embed them even further by adding Prescriptions subdocuments to each of the Diagnosis document.

ignite-me
  • 738
  • 3
  • 14
  • 33

1 Answers1

0

You need to iterate through the diagnosis array.

  @foreach($users as $user)
        @foreach $diagnosis as $user->diagnosis
            {{ var_dump($diagnosis) }}
        @endforeach
    @endforeach
Colin Schoen
  • 2,526
  • 1
  • 17
  • 26
  • This seems to be the right approach, however, the system now returns `ErrorException in CompilesLoops.php line 80: Undefined offset: 1`. I assume that has something to do with using the wrong array offset while retrieving it? – ignite-me Feb 15 '17 at 10:48