2017-04-20 133 views
0

我試圖在我的應用程序中註冊,但發生了此錯誤,我不知道爲什麼。 enter image description here嘗試在laravel 5.4中獲取非對象錯誤的屬性

和我post.blade.php文件中有這樣的代碼:

<div class="blog-post"> 
<h2 class="blog-post-title"> 

    <a href="/posts/{{$post->id}}"> 

     {{$post->title}} 

    </a> 

</h2> 


<p class="blog-post-meta"> 

    {{$post->user->name }} 
    {{$post->created_at->toFormattedDateString()}} 


</p> 

{{$post->body}} 

PostController中有這樣的代碼:

public function index() 

    { 
     $posts=Post::latest()->get(); 

    return view('posts.index',compact('posts')); 
    } 

和索引文件是:

@foreach($posts as $post) 
     @include('posts.post') 
    @endforeach 

    <nav class="blog-pagination"> 
     <a class="btn btn-outline-primary" href="#">Older</a> 
     <a class="btn btn-outline-secondary disabled" href="#">Newer</a> 
    </nav> 

</div><!-- /.blog-main --> 
+0

您是否從控制器傳遞'$ post'? –

+0

檢查您是否傳遞$ post變量。 –

+0

您確定created_at實際上是發送$ post嗎? – Frenus

回答

1

我覺得你的代碼需要更新,如:

public function index() 
{ 
    $posts=Post::with('users')->latest()->get(); 
    return view('posts.index',compact('posts')); 
} 

<p class="blog-post-meta"> 
    {{$post->users->name }} 
    {{$post->created_at->toFormattedDateString()}} 
</p> 

希望這對你的工作!

+0

我檢查了你的答案,但是這個錯誤發生了:調用模型[App \ Post]上的未定義關係[用戶]。 –

0

我假定您在index.blade.php文件中包含post.blade.php

在上述情況下,您未通過$postpost.blade.php。你foreach循環就會像:

@foreach($posts as $post) 
    @include('posts.post', ['post' => $post]) 
@endforeach 
+0

它不適用於我 –

+0

@HanieAsemi你可以'dd()''$ post'。 –

+0

我在哪裏添加這個方法? –

0

假設你要包括在index.blade.php文件post.blade.php。

在上面的情況下,您沒有將$ post傳遞給post.blade.php。你的foreach循環將是這樣的:

@foreach($posts as $post) 
    @include('posts.post', ['post' => $post]) 
@endforeach 
+0

我想這個錯誤是在用戶,因爲其他帖子對象目前工作 –

+0

你嘗試了我的方式回答?? –

+0

是的,但它不適用於我 –

相關問題