title: Display Category Name With Category ID from Product - Laravel
body: <p>I already found this answer but it doesn't work for me (<a href="https://stackoverflow.com/questions/39222584/laravel-displaying-categories-by-id">Laravel - displaying categories by id</a>)</p>
  
  <p>I can't display Category Name in Product List Pages.</p>
  
  <p>My Database:</p>
  
  <p>Category: CategoryID, CategoryName</p>
  
  <p>Product: ProductID, Name, Des, ProductCategoryID</p>
  
  <p>Product Model: </p>
  
  <pre><code>protected $table ='products';
  
  protected $primaryKey = 'ProductID';
  
  public $timestamps = false;
  
  public function Category(){
     return $this-&gt;belongsTo('App\Category','ProductID','CategoryID');
  }
  </code></pre>
  
  <p>Category Model:</p>
  
  <pre><code>protected $table = 'productcategories';
  
  public function Product(){
    return $this-&gt;hasMany('App\Product','ProductCategoryID','ProductID');
  }
  </code></pre>
  
  <p>My Controller:</p>
  
  <pre><code> public function danhsachsanpham(){
  
  $sanpham = Product::all();
  return view('admin/products/danhsach', ['sanpham'=&gt; $sanpham]);
  </code></pre>
  
  <p>}</p>
  
  <p>My Views:</p>
  
  <pre><code>            &lt;table class="table table-striped table-bordered table-hover" id="dataTables-example"&gt;
              &lt;thead&gt;
                  &lt;tr align="center"&gt;
                      &lt;th&gt;ID&lt;/th&gt;
                      &lt;th&gt;Name&lt;/th&gt;
                      &lt;th&gt;Description&lt;/th&gt;
                      &lt;th&gt;Category Name&lt;/th&gt;                        
                  &lt;/tr&gt;
              &lt;/thead&gt;
              &lt;tbody&gt;
              &lt;?php foreach ($sanpham as $sp): ?&gt;
                   &lt;tr class="odd gradeX" align="center"&gt;
                      &lt;td&gt;{{$sp-&gt;ProductID}}&lt;/td&gt;
                      &lt;td&gt;{{$sp-&gt;ProductName}}&lt;/td&gt;
                      &lt;td&gt;{{$sp-&gt;ProductLongDesc}}&lt;/td&gt;
                      &lt;td&gt;{{$sp-&gt;ProductCategoryID-&gt;CategoryName}}&lt;/td&gt;
                  &lt;/tr&gt;
              &lt;?php endforeach ?&gt;
              &lt;/tbody&gt;
          &lt;/table&gt;
  </code></pre>
  
  <p>And I get an Error:</p>
  
  <pre><code>Trying to get property of non-object (View: C:\xampp\htdocs\banhang\resources\views\admin\products\danhsach.blade.php)
  </code></pre>
  
  <p>Where I was wrong ? Please show me how to fix it.</p>
  
  <p>Thanks</p>