View related table information - Laravel?

Asked

Viewed 152 times

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!

  • 1

    @Virgilionovic edited the question and put the model of the product and the category

  • I made the reply and attached a few more ...

  • It worked, man!?

  • 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

  • Remove :belongsTo the end of the methods and hasMany also like I did in editing should be PHP version

  • 1

    Dude, it worked now. Thank you so much for helping! You’re great! Congratulations!

Show 2 more comments

1 answer

1


The answer is as follows:

In his Controller put the load in advance with the method with, because in this way two SQL only and with it has a better performance than the delayed loading that at each interaction makes a SQL for each item brought, then change:

public function index()
{
    $registros = Produto::with('categoria')->get();    
    return view('produtos.index',compact('registros'));
}

In the stretch of View change:

@foreach ($registros as $registro)
<tr>
    <td>{{$registro->id}}</td>
    <td>{{$registro->nome}}</td>
    <td>{{$registro->categoria->nome}}</td>
</tr>
@endforeach

I also like to configure keys, example:

Model Produto:

class Produto extends Model
{
    protected $fillable = [
        'nome', 'descricao','codigo',
        'imagem','quantidade','valor',
        'categoria_id','publicado',
    ];

    public function categoria()
    {
        return $this->belongsTo(Categoria::class,'categoria_id','id');
    }
}

Model Categoria:

class Categoria extends Model
{
    protected $fillable = [
        'nome', 'descricao',
    ];

    public function produtos()
    {
        return $this->hasMany(Produto::class,'categoria_id','id');
    }
}

having certainty of relationships, but, can also be used the standard conventions of Eloquent ORM hassle-free.

Related matters:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.