title: Trying to get property of non-object Error - Laravel
body: <p>I'm developing a blog in laravel and I'm having trouble with foreign keys between two tables: <code>posts</code> and <code>categories</code>.</p>
  
  <p>I created two models: <code>Post</code> (for the posts table) and <code>Category</code> (for the categories table). In my view I wrote this code : <code>&lt;p&gt;Posted In: {{$post-&gt;category-&gt;id}}&lt;/p&gt;</code>, but this error is showing : </p>
  
  <blockquote>
    <p><strong>ErrorException:</strong> Trying to get property of non-object foreign key error</p>
  </blockquote>
  
  <p>Post Model :</p>
  
  <pre><code>class Post extends Model
  {
      public function category()
       {
          return $this-&gt;belongsTo('App\Category');
      }
  }
  </code></pre>
  
  <hr>
  
  <p>Category Model :</p>
  
  <pre><code>class Category extends Model
  {
      public $table = 'categories';  
  
      public function posts() 
      { 
          return $this-&gt;hasMany('App\Post');
      }
  }
  </code></pre>
  
  <hr>
  
  <p>View form : </p>
  
  <pre><code>@extends('main')
  
  @section('title', "| $post-&gt;title " )
  
  @section('content')
  
      &lt;div class="row"&gt;
          &lt;div class ="col-md-8&gt;&lt;/col-md-8 col-md-offset-2"&gt; 
              &lt;h1&gt;{{$post-&gt;title}}&lt;/h1&gt;
              &lt;p&gt;{{$post-&gt;body}}&lt;/p&gt;
              &lt;hr&gt;
              &lt;p&gt;Posted In:{{$post-&gt;category-&gt;id}}&lt;/p&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  @endsection
  </code></pre>
  
  <p>I expect that the code : <code>&lt;p&gt;Posted In: {{$post-&gt;category-&gt;id}}&lt;/p&gt;</code> 
  will  output the category in the blog post.</p>