Reputation: 35
Hi i'm working on a laravel training project . i'm having an issue with models and relationships when i'm trying to get the each product category name .
Here is my Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
and my Category model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function products()
{
return $this->hasMany('App\Product');
}
}
when i try to get the category name for each product like this
@foreach($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->category->name }}</td>
</tr>
@endforeach
while i run the page i get this error
Undefined property: stdClass::$category (View: /var/www/html/projectname/resources/views/my/products/index.blade.php)
can anyone tell me what's causing this error ?
update
here is the table structure
Products : id , name , category_id->unsigned()
Categories : id , name
and here is the code i use to get $products
$user_id = Auth::user()->id;
$products = DB::table('products')->where('user_id', $user_id)->paginate(5);
return view('my.products.index')->withProducts($products);
Upvotes: 0
Views: 5414
Reputation: 16283
Your issue is that you're using Laravel's query builder instead of Eloquent, but you're treating the result as if it was Eloquent.
When you do:
$products = DB::table('products')->where('user_id', $user_id)->paginate(5);
The $products
variable will contain a Paginator
instance, which contains your items as instances of stdClass
. If you want to be able to do this with Eloquent, you should try something like this:
$products = Product::with('category')->where('user_id', $user_id)->paginate(5);
This will ensure that the items returned in the paginator are instances of your Product
Eloquent model, with the category
relationship eager loaded (I.e. it will load the category relationship for each Product
returned using one query, rather than 5 queries, one for every Product
).
You should then be able to access $product->category->name
.
Upvotes: 8