Laravel 5.2 Trying to get property of non-object

Viewed 744

I am following tutorial to make blog project on laravel 5.2, i am trying to show the user name from other table (users table). The post properties is shown successfully in the view, but i got Trying to get property of non-object when i try to access property from uses table.

Here is my view:

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

          </div><!-- /.blog-post -->

and here is my postscontroller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\User;

use App\Http\Requests;



class PostsController extends Controller
{
    //
  public function __construct(){
    $this->middleware('auth')->except(['index','show']);
  }

    public function index(){


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

    public function show($id){

        $post = Post::find($id);
        return view('posts.show',compact('post'));
    }

    public function create(){
        return view('posts.create');
    }

   public function store(){
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required'

        ]);

    Post::create([
      'title' => request('title'),
      'body' => request('body'),
      'user_id' => auth()->id()
      ]);


    // $post = new Post;
    // $post->user_id = auth()->id()
    // $post->title = request('title');
    // $post->body = request('body');


    // $post->save();

    return redirect('/');

   }
}

here is the post model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
    protected $fillable = ['title','body','user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments(){
        return $this->hasMany(Comment::class);
    }



}

user model:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts(){
        return $this->hasMany(Post::class);
    }
}
1 Answers
Related