i know this question already asked before. But i still can't understand how it works, so i ask again. The title explain my question everything.
I have 2 tables, products
and product_types
in products
id
name
type_id
in product_types
id
type_name
Here's my Product
Model
class Product extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
public function productType() {
return $this->hasOne('App\ProductType', 'type_id');
}
}
Here's my ProductType
Model
class ProductType extends Model
{
protected $table = 'product_types';
protected $primaryKey = 'id';
public function product() {
return $this->hasMany('App\Product');
}
}
Here's my Controller for my view
public function viewManageProduct() {
$products = Product::all();
$productTypes = ProductType::all();
return view('manages.products')->with(['products' => $products]);
}
my View
@foreach ($products as $product)
<table>
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->productType->type_name }}</td>
</tr>
</table>
@endforeach
I don't know how to access the type_name
. Can anyone help? Thanks in advance