Reputation: 548
I already found this answer but it doesn't work for me (Laravel - displaying categories by id)
I can't display Category Name in Product List Pages.
My Database:
Category: CategoryID, CategoryName
Product: ProductID, Name, Des, ProductCategoryID
Product Model:
protected $table ='products';
protected $primaryKey = 'ProductID';
public $timestamps = false;
public function Category(){
return $this->belongsTo('App\Category','ProductID','CategoryID');
}
Category Model:
protected $table = 'productcategories';
public function Product(){
return $this->hasMany('App\Product','ProductCategoryID','ProductID');
}
My Controller:
public function danhsachsanpham(){
$sanpham = Product::all();
return view('admin/products/danhsach', ['sanpham'=> $sanpham]);
}
My Views:
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr align="center">
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($sanpham as $sp): ?>
<tr class="odd gradeX" align="center">
<td>{{$sp->ProductID}}</td>
<td>{{$sp->ProductName}}</td>
<td>{{$sp->ProductLongDesc}}</td>
<td>{{$sp->ProductCategoryID->CategoryName}}</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
And I get an Error:
Trying to get property of non-object (View: C:\xampp\htdocs\banhang\resources\views\admin\products\danhsach.blade.php)
Where I was wrong ? Please show me how to fix it.
Thanks
Upvotes: 0
Views: 6424
Reputation: 11
Replace : $sanpham = Product::all();
by : $sanpham = Product::with('category')->get();
then on your view: $sp->category->CategoryName
the best answer for optimisation (number of queries ):
$sp->category->CategoryName
Upvotes: 0
Reputation: 1
I would like to update the answer according to Laravel 8.
Product Model:
public function Category()
{
return $this->belongsTo('App\Models\Category', 'ProductCategoryID', 'CategoryID');
}
Category Model:
public function Products()
{
return $this->hasMany('App\Models\Product', 'ProductCategoryID');
}
Upvotes: 0
Reputation: 5358
You'd get the CategoryName through the Category()
relationship method:
<td>{{$sp->Category()->first()->CategoryName}}</td>
Or shorter:
<td>{{$sp->Category->CategoryName}}</td>
Edit: Your relationships methods are using wrong foreign keys. Try:
Product Model:
public function Category()
{
return $this->belongsTo('App\Category', 'ProductCategoryID', 'CategoryID');
}
Category Model (note plurality naming of the method: Products) :
public function Products()
{
return $this->hasMany('App\Product', 'ProductCategoryID');
}
Upvotes: 4