you can in the model Categoria
(assuming that it is called), create the
next method
In this first one we have the relation hasMany()
because it is understood that a category has many products associated with it
public function productos()
{
return $this->hasMany(Producto::class);
}
It is obvious that you will have to put where I put Producto::class
the name that you gave to your model where you manage the table products
Later in the model Producto
, do the following
In this part I use the relation belongsTo()
because it is understood that a product belongs to a category
public function categoria()
{
return $this->belongsTo(Categoria::class);
}
I explain.
To access these values, the following is done in the view
@foreach($productos as $producto)
{{ $producto->nombre }}
{{ $producto->precio }}
{{ $producto->categoria->name }}
@endforeach
Please note the categoria->name
refers to the categoria
method and the categoria
table and the name
of that table
Here the source of official consultation, the Laravel documentation
link