What is missing really in your question are the relations of your two tables, and also the Models
which are configured for these tables, where a Produto
has Categoria
and a Categoria
is in several Produto
, that is to say, a 1:N relationship. A fictional example about a product table and a category table where the two relate, example:
Classes:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
protected $table = 'produtos';
protected $fillable = ['categoria_id','descricao'];
public function categoria()
{
return $this->belongsTo(App\Categoria::class,'categoria_id','id');
}
}
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Categoria extends Model
{
protected $table = 'categorias';
protected $fillable = ['nome'];
public function produtos()
{
return $this->hasMany(App\Produto::class,'categoria_id','id');
}
}
How to use:
public function index()
{
$prod = Produto::with('categoria')->get();
return view('produtos', compact('prod'));
}
@foreach ($prod as $p)
<tr>
<td>{{$p->id}}</td>
<td>{{$p->descricao}}</td>
<td>{{$p->categoria->nome}}</td>
</tr>
@endforeach
In this example there are several important points:
Create entities' relationship by explicitly specifying the keys (if following the names you do not need to put, but, it is a good conduct to put mainly for maintenance)
Load forward interface (command with('categoria')
), because, there is the optimization of only 2 queries SQL
different from the other that each interaction and made a new query SQL
causing slowness and a very common error in development with Laravel
.
Ref.
Could [Dit] the question putting the class
Produto
, mainly showing how implemented the relationship between the models?– Woss