I am making an inventory system with Laravel 9, and I have a 'categories' table that is associated with a 'products' table since these fall into the categories that one creates. The category id is stored in the product and what I want is that in the index where the data is displayed, instead of showing the category id number, it shows me the name.
Model Product
public function categorias(){
return $this->belongsTo(Categoria::class, 'id');
}
Model Category
public function productos(){
return $this->hasMany(Producto::class, 'id_cat');
}
ProductController
public function index()
{
$categorias = Categoria::all();
$productos = Producto::with('categorias')->get();
return view('producto.index', compact('categorias','productos')); //->with('productos',$productos);
}
View
<table id="productos" class="table table-striped table-dark table-bordered shadow-lg nt-4">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Imagen</th>
<th scope="col">Código</th>
<th scope="col">Categoría</th>
<th scope="col">Descripción</th>
<th scope="col">Stock</th>
<th scope="col">Solicitado</th>
<th scope="col">Acciones</th>
</tr>
</thead>
<tbody>
@foreach ($productos as $producto)
<tr>
<td>{{$producto->id}}</td>
<td>{{$producto->imagen}}</td>
<td>{{$producto->codigo}}</td>
<td>{{$producto->categoria->categoria}}</td>
<td>{{$producto->descripcion}}</td>
<td>{{$producto->cantidad}}</td>
<td>{{$producto->solicitudes}}</td>
<td>
<form action="{{route ('productos.destroy',$producto->id)}}" method="POST">
<a href="/productos/{{ $producto->id}}/edit" class="btn btn-info">Editar</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Borrar</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
In my ignorance, I understand that what is wrong would be
<td>{{$producto->categoria->categoria}}</td>
because there really isn't a 'category' in products, but I don't know how to make del id_cat = categoria.id
take the name of the category, the error it gives me is the following:
Attempt to read property "categoria" on null
When a relationship is made within the models of each table, a name is assigned to the function so that they can be used at another time
In your case the name of the relation you are trying to query is
categorias
that is seen here
Then, to be able to use that relationship within a query, use
->with(nombre_relacion)
And indeed you are calling the categories function, that is seen here
Your only mistake is here
Since the correct call would
'la variable que hace la consulta' -> 'el nombre de la funcion que crea la relación' -> 'el nombre del campo de esa tabla relacionada que deseas consultar'
be , being as follows, taking into account that in your categories table there is a field called categoryIn a few words you only ate the
s
but it is good to break down the reason for the errorEDIT-------------------------