- Created the
Product
Model with migration
- To use a modifying column with migration, we installed a package named
doctrine/dbal
- Added foreign key field in
Product
table with the help of 2 lines in migration as we know foreign key always take reference from the other table
- In the
Product
Model we created a relationship with belongsTo
function
class Product extends Model
{
use HasFactory;
// Create relationship of 1 to 1 with Category Model (Category::class)
public function category()
{
return $this->belongsTo(Category::class);
}
}
- Render product category inside the view with
<h1>{{ $product->category->name }}</h1>
- For performance reason we are adding condition with the help of
with()
method to load the relationship inside the Controller
$allCategories = Category::all();
$allProducts = Product::with('category')->get();