ahmadbadpey's avatar

Trying to get property of non-object when accessing a Collection in View

I wrote a Controller to send Post Model along with it's Categories and Pics:

class HomeController extends Controller
    {
        public function index ()
        {

            $latestPosts =
                Post::with([
                    'latestPicture',
                    'categories' => function ($query) {
                        $query->select(['categories.cat_id', 'name']);
                    }
                ])
                    ->take(12)->orderBy('created_at', 'desc')
                    ->get(['post_id', 'post_title', 'post_alias', 'post_content', 'comments_count', 'created_at']);
//          dd($latestPosts) ;
            return view('main.pages.home', ['latestPosts' => $latestPosts]);
        }
    }

And for use latestPosts in My View I write this:

@if (!$latestPosts->isEmpty())
    @foreach($latestPosts as $post)
        @if( key($latestPosts) <3)
            <!-- Some HTML -->
        @endif
    @endforeach
@endif

but I faced this Error :

Trying to get property of non-object (View: D:\wamp\www\TC\resources\views\main\pages\home.blade.php)

What is Problem? How Can I access to that Collection in the View?

0 likes
4 replies
bobbybouwmann's avatar

You can debug what is missing here

@if (!$latestPosts->isEmpty())

    {{ dd($latestPosts) }}

    @foreach($latestPosts as $post)

        {{ dd($post) }}

        {{ dd(key($latestPosts)) }}

        @if( key($latestPosts) <3)
            <!-- Some HTML -->
        @endif
    @endforeach
@endif

Refresh and see how far you get. Remove the dd when you get the correct data, from there you can see where the bug is ;)

1 like
ahmadbadpey's avatar

This :

@if (!$latestPosts->isEmpty())
    @foreach($latestPosts as $post)

        {{ dd(key($latestPosts)) }}

        @if( key($latestPosts) <3)
            <!-- Some HTML -->
        @endif
    @endforeach
@endif

returns :

"\x00*\x00items"

I don't know what it say. But I want to get index of current Items Collection ?how can I do ?

ahmadbadpey's avatar
ahmadbadpey
OP
Best Answer
Level 2

I found that have a Typo in Accessing to Property of Post Model in My view.

I must to use latestPicture name instead of latest_picture.

I correct it and All things works fine.

Please or to participate in this conversation.