1
I’m starting to mess with Laravel(5.7) and I’m having a little trouble. I have two tables, product and category, being that one category can be of various products, and the product only of one category.
I’m listing the products, but I can’t show what category it is.
Code that is in the controller:
public function index()
{
$registros = Produto::all();
return view('produtos.index',compact('registros'));
}
Code in view(only the foreach part):
@foreach ($registros as $registro)
<tr>
<td>{{ $registro->id}}</td>
<td>{{ $registro->nome}}</td>
<td>{{ $registro->categoria}}</td> {{--Aqui gostaria de exibir o atributo nome da tabela categoria --}}
</tr>
@endforeach
Model Produto:
class Produto extends Model
{
protected $fillable = [
'nome', 'descricao',
'codigo','imagem','quantidade',
'valor','categoria_id','publicado',
];
public function categoria(): BelongsTo
{
return $this->belongsTo(Categoria::class);
}
}
Model Categoria:
class Categoria extends Model
{
protected $fillable = [
'nome', 'descricao',
];
public function produtos(): HasMany{
return $this->hasMany(Produto::class);
}
}
I come from ASP.NET C#
, there I would do so:
@Registro.Categoria.nome
How do I do something similar to that in Laravel
?
If you can put the Product model and the Category model? so I can put the answer to what you need ... you have two adjustments to make!
– novic
@Virgilionovic edited the question and put the model of the product and the category
– Igor Marcante
I made the reply and attached a few more ...
– novic
It worked, man!?
– novic
When I put the query like this: $records = Product::with('category')->get(); it gives the following error: Symfony Component Debug Exception Fatalthrowableerror (E_RECOVERABLE_ERROR) Return value of App Product::category() must be an instance of Illuminate Database Eloquent Model Belongsto, instance of Illuminate Database Eloquent Relations Belongsto returned
– Igor Marcante
Remove :belongsTo the end of the methods and hasMany also like I did in editing should be PHP version
– novic
Dude, it worked now. Thank you so much for helping! You’re great! Congratulations!
– Igor Marcante