When I try to list products in the blade template I get an error “Attempt to read property “name” on int“
In the blade template I pass the data as follows
<tbody>
@foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->category->name }}</td>
<td>{{ $product->subcategory->name }}</td>
</tr>
@endforeach
</tbody>
My ProductsController.php
public function create(): View
{
$products = Products::with(['category', 'subcategory'])->get();
return view('products', compact('products'));
}
Models Products, Category, SubCategory
class Products extends Model
{
use HasFactory;
protected $table = 'products';
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function subcategory(): BelongsTo
{
return $this->belongsTo(SubCategory::class);
}
}
class SubCategory extends Model
{
use HasFactory;
protected $table = 'subcategory';
public function products(): HasMany
{
return $this->hasMany(Products::class, 'subcategory', 'id');
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, 'id_category', 'id');
}
}
class Category extends Model
{
use HasFactory;
protected $table = 'category';
public function subCategories(): HasMany
{
return $this->hasMany(SubCategory::class, 'id_category');
}
public function products(): HasMany
{
return $this->hasMany(Products::class, 'category', 'id');
}
}
I’m at a loss, I really don’t know what to do anymore. I’m 90% sure I’m making a mistake somewhere in the models, in defining the relationship between the tables. But I’m not 100% sure. The worst part is that neither Google Gemini nor ChatGPT solved my problem, despite 2 hours of trying.
CREATE TABLE `ala_products` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`category` int(10) unsigned NOT NULL,
`subcategory` bigint(20) unsigned NOT NULL,
`color_1` varchar(10) NOT NULL,
`color_2` varchar(10) NOT NULL,
`min_size` smallint(6) NOT NULL DEFAULT 0,
`max_size` smallint(6) NOT NULL DEFAULT 0,
`order_x` smallint(6) NOT NULL DEFAULT 0,
`active` enum('0','1') NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ala_products_category_foreign` (`category`),
KEY `ala_products_subcategory_foreign` (`subcategory`),
CONSTRAINT `ala_products_category_foreign` FOREIGN KEY (`category`) REFERENCES `ala_category` (`id`),
CONSTRAINT `ala_products_subcategory_foreign` FOREIGN KEY (`subcategory`) REFERENCES `ala_subcategory` (`id`)