Question:
Well I'm working with the framework Laravel
in versão 5.2
I'm developing an API
where I have an Painel administrativo
that produces and manages the content, in this case produto
, and I have another site that will consume this API do painel administrativo
where it has to list all the products.
Within the produto
I have several items such as: images, category, subcategory, among others. I'm consuming this API
via JQUERY
the command $.getJSON()
. However I am having problems accessing my product items such as images.
In my Model produto
I did it as follows:
use SoftDeletes;
protected $fillable = [
'CdSubCategoria',
'NmProduto',
'DscProduto',
'VlUnit',
'UnitEmEstoque',
'FlgDescontinuado',
'FlgProdutoVisivel',
'Visivel_Ini',
'Visivel_Fim',
'FlgPontua',
'QtdPontos',
'MaxPontosPorSubCategoria'
];
protected $primaryKey = 'CdProduto';
protected $dates = ['deleted_at'];
public function subCategoria()
{
return $this->belongsTo('App\SubCategoria','CdSubCategoria','CdSubCategoria');
}
public function imagens(){
return $this->hasMany('App\Imagem', 'CdProduto', 'CdProduto');
}
public function lotes(){
return $this->hasMany('App\LoteProduto', 'CdProduto', 'CdProduto');
}
public function tipo_produto_embalagem(){
return $this->belongsTo('App\TipoProdutoEmbalagem', 'CdProduto', 'CdProduto');
}
In my Controller Produto
which is where I access with $.getJSON()
I did the following, an index()
function that identifies the first metodo
of my controller
:
public function index(){
$produtos = Produto::all();
if(Request::wantsJson()){
return compact('produtos');
}else{
return view('Produto.listProduto', compact('produtos'));
}
}
My return compact('produtos')
is what it sends when I make the requisição
.
On my site I'm getting this array
and I do an .each()
on my váriavel
inside this .each()
that I'm trying to access my product items as images.
My code is like this:
$.getJSON('http://localhost:8000/produtos', function(data) {
$('#todosProdutos').html('');
$.each(data, function (key, item) {
var ANTIGO = $('#todosProdutos').html();
console.log(item.imagens); //Aqui dei um console para tentar verificar as imagens porém retorna undefined
var html = ANTIGO + 'MEU HTML';
});
//console.log(html);
// $('#todosProdutos').html(html);
console.log(data);
});
In my console.log(item.imagens)
's returning undefined
which part of the process am I missing? I tried to access others as a category, and it's not working either.
When I give console.log(item)
it only returns the items that are actually in the same product table, for example:NmProduct, VlUnit, UnitEmStock, among others.
Answer:
In Laravel there are two ways to load the relationship: eager loading constraints and lazy loading .
The first, which is eager loading constraints , loads relationships early, before accessing the values of the defined relationships. The second, lazy loading , only accesses when you call the relationship.
It is not possible to use lazy loading for JSON
. So, when it comes to Ajax requests, I recommend always using eager loading constraints so that the relationship data will always be available.
This operation is done through the with
method.
Look:
public function index(){
$produtos = Produto::with('imagens')->get();
if(Request::wantsJson()){
return compact('produtos');
}else{
return view('Produto.listProduto', compact('produtos'));
}
}