I am creating a simple inventory system using larvel 7. I ran in to the problem with
Call to undefined relationship [products] on model [AppCategory].
I am creating a two tables category and products I want have relationship with them.
Category table
id categoryname
1 drink
2 biscuits
3 toy
product table
id productname category
1 fanta 1
2 apple juice 1
3 buildblocks 3
I need to category table and product table look like this this and get the data and passing to the table. I need this below output:
id productname categoryname
1 fanta drink
While I am running the program I got this error:
Call to undefined relationship [products] on model [AppCategory].
I don't know why it has happing. What I tried so far I attached below.
Model
Category
class Category extends Model
{
protected $fillable = [
'categoryname',
];
}
Product
class Product extends Model
{
protected $fillable = [
'product_name',
'category',
];
public function category (){
return $this->belongsTo('AppModelsCategory','category','id');
}
}
view.blade.php
<tbody>
@foreach ($products as $key => $product)
<tr>
<td>{{$key}}</td>
<td>{{$product->product_name}}</td>
<td>{{$product->category->categoryname}}</td>
</tr>
@endforeach
</tbody>
Routes
Route::get('/products', 'ProductController@view')->name('product.view');
ProductController
<?php
namespace AppHttpControllers;
use AppProduct;
use AppCategory;
use IlluminateHttpRequest;
class ProductController extends Controller
{
public function view()
{
$products = Product::with('category')->get();
dd($products);
$categories = Category::with('products')->get();
return view ('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…