Advertisement
nguyen47

DIsplay Category Name with ID

Jan 7th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.44 KB | None | 0 0
  1. My Database:
  2.  
  3. Category: CategoryID, CategoryName
  4.  
  5. Product: ProductID, Name, Des, ProductCategoryID
  6.  
  7. Product Model:
  8.  
  9. public function Category(){
  10.    return $this->belongsTo('App\Category','ProductID','CategoryID');
  11. }
  12.  
  13. Category Model:
  14.  
  15. public function Product(){
  16.   return $this->hasMany('App\Product','ProductCategoryID','ProductID');
  17. }
  18.  
  19. My Controller:
  20.  
  21. public function danhsachsanpham(){
  22.  
  23. $sanpham = Product::all();
  24. return view('admin/products/danhsach', ['sanpham'=> $sanpham]);
  25.  
  26. Views:
  27.  
  28. <table class="table table-striped table-bordered table-hover" id="dataTables-example">
  29.             <thead>
  30.                 <tr align="center">
  31.                     <th>ID</th>
  32.                     <th>Name</th>
  33.                     <th>Description</th>
  34.                     <th>Category Name</th>                        
  35.                 </tr>
  36.             </thead>
  37.             <tbody>
  38.             <?php foreach ($sanpham as $sp): ?>
  39.                  <tr class="odd gradeX" align="center">
  40.                     <td>{{$sp->ProductID}}</td>
  41.                     <td>{{$sp->ProductName}}</td>
  42.                     <td>{{$sp->ProductLongDesc}}</td>
  43.                     <td>{{$sp->ProductCategoryID->CategoryName}}</td>
  44.                 </tr>
  45.             <?php endforeach ?>
  46.             </tbody>
  47.         </table>
  48.  
  49. And I get an Error:
  50.  
  51. Trying to get property of non-object (View: C:\xampp\htdocs\banhang\resources\views\admin\products\danhsach.blade.php)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement