Sebastian M
Sebastian M

Reputation: 491

Accessing multidimensional array in blade

Each student has a user (one to one), languages and hobbies (both many to many).

A match is composed by two students (self relationship)

I wan to fill a multidimensional array with the matchId, all the info about the first student and all about the second. I'm populating it array this way:

$matches = Match::getMatches($semester->id);
  
foreach ($matches as $m)
    {
         $profiles[] = array(  
            'matchId' =>  $m->matchId,
            'local'   =>  Student::with('user', 'language', 'hobby')->where('user_id', $m->localUserId)->first(),
            'incoming'=>  Student::with('user', 'language', 'hobby')->where('user_id', $m->incomingUserId)->first());
    }

Now I want to access that data in a blade template but cannot succeed.

{{ $profiles['local'] }}

works, but when adding something like

{{ $profiles['local']['email'] }}

I get nasty errors.

Any hints?

Upvotes: 2

Views: 1955

Answers (1)

jszobody
jszobody

Reputation: 28911

You don't currently have a multidimensional array. You are storing an Eloquent database result object in $profiles['local'], an instance of the Student class.

So you'll need to access it like this:

{{ $profiles['local']->email }}

Alternatively you could put a toArray() at the end when you fetch the student:

Student::with(...)->where(...)->first()->toArray(),

Now you would have a raw PHP array, and could access it like you originally attempted:

{{ $profiles['local']['email'] }}

Side note: when you don't understand how to navigate something, try using dd to inspect it.

<?php dd($profiles['local']); ?>

That would show you that you have an instance of Student, and help you understand how to navigate it.

Upvotes: 5

Related Questions