Hanie Asemi
Hanie Asemi

Reputation: 1500

Trying to get property of non-object error in laravel 5.4

I'm trying register in my app but this Error happened and I don't know why. enter image description here

and my post.blade.php file has this code:

<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 has this code:

public function index()

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

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

and index file is:

    @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 -->

Upvotes: 0

Views: 361

Answers (3)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

I think your code need to update like:

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>

Hope this work for you!

Upvotes: 1

Pankit Gami
Pankit Gami

Reputation: 2553

I assume that you are including post.blade.php in index.blade.php file.

In above case you are not passing $post to post.blade.php. Your foreach loop will be like :

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

Upvotes: 0

Abdou Rayes
Abdou Rayes

Reputation: 430

assume that you are including post.blade.php in index.blade.php file.

In above case you are not passing $post to post.blade.php. Your foreach loop will be like :

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

Upvotes: 0

Related Questions