Laravel: Access relationship attributes

1

I have the products , images tables, image_products tables.  The image_products table has a foreign key to the products and images table.

When I list the products and names of the images that are in the images table with the command below, I can not:

foreach($produtos as $produto) {
   echo $produto->imagens->first()->id;
}

But it works if I access it like this:

foreach($produtos as $produto) {
   echo $produto->imagens->first()['id'];
}

I'm used to access the other relationships first, but in this one of the images the error returns:

Trying to get property of non-object

Controller

$produtos = Produto::get();

Model Product

public function imagens()
{
    return $this->HasMany('App\ProdutoImagem');
}

Model ProductImaging

public function imagem()
{
    return $this->belongsTo('App\Imagem');
}

DD (part of relations)

#relations: array:1 [▼
"imagens" => Collection {#255 ▼
  #items: array:1 [▼
    0 => ProdutoImagem {#260 ▼
      #table: "produtos_imagens"
      #fillable: array:3 [▶]
      +timestamps: false
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:4 [▶]
      #original: array:4 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "imagem" => Imagem {#269 ▼
          #table: "imagens"
          #fillable: array:2 [▶]
          +timestamps: false
          #connection: "mysql"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:3 [▶]
          #original: array:3 [▶]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
      ]
    
asked by anonymous 07.07.2018 / 06:17

0 answers