Object property from JSON is not accessible

Asked

Viewed 145 times

3

Well I’m working with the framework Laravel in versão 5.2 I’m developing a API where I have a Painel administrativo that produces and manages the content in the case in question produto, and I have another site that will consume this API do painel administrativo where she has to list all products.

Within produto have several items like: images, category, subcategory, among others. I am consuming this API via JQUERY performing the command $.getJSON(). However I am having problems accessing my product items such as images.

In my Model produto I did it this way:

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 access with $.getJSON() I did the following, a function index() identifying the first metodo of mine controller:

public function index(){
    $produtos =  Produto::all();

    if(Request::wantsJson()){
        return compact('produtos');
    }else{
        return view('Produto.listProduto', compact('produtos'));
    }
}

Man return compact('produtos') is what you send when I requisição.

On my website I’m getting this array and make a .each() in my váriavel within this .each() I am trying to access my product items as images.

My code is as follows:

   $.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) is returning undefined in which part of the process am I missing ? I tried to access others as a category, and it is also not working.

When I give console.log(item) it returns only the items that actually are in the same product table, as example: Nmproduct, Vlunit, Unitemestoque, among others.

2 answers

1

Missed carrying relationship, this is not automatic as it was done:

With the command with of , relationships are born:

public function index()
{
    $produtos =  Produto::with('imagens')
                         ->get();

    if(Request::wantsJson())
    {
        return compact('produtos');
    }

    return view('Produto.listProduto', compact('produtos'));
}

If by chance you need to load the other relationships add ->with('') with the name of relationships:

Example:

$produtos =  Produto::with('imagens')
                    ->with('lotes')
                    ->get();

or with a array

$produtos =  Produto::with(['imagens','lotes'])
                    ->get();

1


In Laravel there are two ways to carry the relationship: Eager loading constraints and Lazy loading.

The first, which is Eager loading constraints (anxious loading, load the relationships in advance, before accessing the values of the relationships defined. Already the second, Lazy loading (lazy loading), only access when you call the relationship.

Unable to use Lazy loading for JSON. So when it comes to Ajax requests, I always recommend using Eager loading constraints, so relationship data will always be available.

This operation is done through the method with.

Behold:

public function index(){
    $produtos =  Produto::with('imagens')->get();

    if(Request::wantsJson()){
        return compact('produtos');
    }else{
        return view('Produto.listProduto', compact('produtos'));
    }
}
  • And to access my html as I do ?

  • 1

    Um... that’s not in the question, but you can just do $produto->imagens within the foreach with $produtos. If you need more details it would be better to ask another question.

  • I already did, I’m even having problems with this also look so http://answall.com/questions/157691/problema-com-each-jquery

  • @Renanrodrigues $produto->imagens returns a collection, has to scan that list. As Wallace Maxters quoted and you said yourself, it would be another question (the question has already been asked)

  • Are you talking about html handling with jQuery or Blade? Now I’m confused.

  • There in the case I am with jquery, because the idea is that they will be on different servers, actually this kind of confused for me still, however I am using jquery

  • @Wallacemaxters How do I make this request with Blade ? and the bargain for me ? This is not clear

  • 2

    @Virgilionovic this situation reminded me his question on the goal. Including I drew up a reply for you

Show 3 more comments

Browser other questions tagged

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