访问视图中的集合时,正在尝试获取非对象的属性


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

我写了一个控制器来发送Post Model及其类别和图片:

    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]);
        }
    }

为了在我的视图中使用latestPosts,我写了这样的文章:

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

但我遇到了这个错误:

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

什么是问题?如何访问视图中的集合?

我发现在我的视图中访问Post Model的属性时有一个Typo。

我必须使用latestPicture名称,而不是latest_picture

我改正了,一切都很好。

我更愿意做的两件事与您现有的不同,这可能会消除您的错误,因为您不必使用isEmpty()属性。您可以使用@forelse来代替@if语句,例如:

@forelse($latestPosts as $key => $post)
    @if($key <= 3)
    <!-- Some HTML -->
    @endif
@empty
@endforelse

如果isEmpty()属性可用,我宁愿使用:

@unless($latestPosts->isEmpty())
    @foreach()
    @endforeach
@endunless

而不是CCD_ 3,但后者只是为了拥有更清晰、更易于阅读的代码。粘贴dd($latestPosts)的结果将使调试更加容易。即使你已经更正了拼写错误,我也花了更长的时间来发布这篇文章,我认为你应该考虑

中提到的一些事情