Support the ongoing development of Laravel.io →
Eloquent Views Blade
Last updated 2 years ago.
0

PascalKleefeld said:

       @foreach($links as $link)
           <p><a href="{{ $link->link }}">{{ $link->link }}</a>, {{ $link->cats->get(0)->cat_name}}</p>
       @endforeach

$link->link does work, but $link->cats->cat_name doesn't.

How can i get values from a deeper layer of each array?

Thanks guys! :)

I'm surprised $link->link worked. You're working with associate arrays so you should access them like an array. Also ::get is a Collection method. Your are working with a primitive array so ::get will fail.

        @foreach($links as $link)
            <p><a href="{{ $link['link'] }}">{{ $link['link'] }}</a>, {{ $link['cats'][0][cat_name] }}</p>
        @endforeach

If you remove the ::toArray call your current view implementation should work.

Last updated 2 years ago.
0

Try removing $links->toArray(); statement. I believe you do not need that.

Last updated 2 years ago.
0

Hi, thanks for your answers.

I still can't access 'cats'. My object looks like this:

{"id":1,"user_id":1,"cat_id":3,"link":"http:\/\/www.google.de","active":0,"description":"","created_at":"2014-07-16 19:46:23","updated_at":"2014-07-16 19:46:23",
"cats":[
{"id":1,"cat_name":"Design","created_at":"2014-07-16 00:00:00","updated_at":"2014-07-16 00:00:00","pivot":{"link_id":1,"cat_id":1}}
]}, 

Is this correct? I think i could geht $link->cats->cat_name...But i get the error :

Undefined property: Illuminate\Database\Eloquent\Collection::$cat_name
Last updated 2 years ago.
0

Since there is many cats for every link, Eloquent is returning an collection object. You'd have to either

  • simply loop over all cats (if you want to show them all)
  • use the $link->cats->first()->cat_name which is equivalent to $link['cats'][0]['cat_name']

The collection object is very powerful and convienient to work with. It actually implements the ArrayAccess interface, so if you want you could use the array syntax for it. I recommend reading this http://daylerees.com/codebright/eloquent-collections.

Edit: by the way, it's worth noting that the toArray() returns an array, it does not transform to object to an array. So, in your original code, you were actually passing the original object. This is the reason why the $link->link ever worked.

Last updated 2 years ago.
0

Oh my god, thank you so much christoffertyrefors!

I've spend hours for this. I will read your recommendation.

Thank you!!! :)

Last updated 2 years ago.
0

Welcome to laravel ;)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.