I have three tables (products, categories, sizes) and models (Product, Category, Size) respectively.
In my product table I saved category_id
and size_id
respectively.
For list view I want to fetch category_name
from category table and size_name
using size table respectively.
I am using relation for that purpose. Below is model structure of relationship.
Product:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Product extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
public function size()
{
return $this->belongsTo(Size::class);
}
}
Category:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Category extends Model
{
public function product()
{
return $this->hasMany(Product::class);
}
}
Size:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Size extends Model
{
public function product()
{
return $this->hasMany(Product::class);
}
}
Below is my controller where I want fetch data with category name and size name. Then want to send data to list view with category name and size name to display:
public function productList()
{
// $product = Product::get();
$data = Product::with('categories','sizes')->get();
echo "<pre>";
//print_r($product->category->name);
// return view('admin.productlist',['productdata' => $data]);
}
Below is my migration file of product:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category')->nullable();
$table->string('product_price');
$table->string('product_size')->nullable();
$table->string('product_stock')->nullable();
$table->string('product_description')->nullable();
$table->string('created_user_id')->nullable();
$table->timestamps();
});
Size migration:
Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('product_size');
$table->timestamps();
});
Category Migration :
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Anyone have any idea what I am doing wrong then please help me in that.
My list blade file is below:
@foreach ($productdata as $product)
<tr>
<td>{{$product->product_name}}</td>
<td>{{$product->product_category}}</td>
<td>{{$product->product_size}}</td>
<td>{{$product->product_price}}</td>
</tr>
@endforeach