Laravel: Access Relationship Attributes

Asked

Viewed 281 times

1

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

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

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 accessing the other relations in the first way, but in this picture returns me the error:

Trying to get property of non-object

Controller

$produtos = Produto::get();

Model Produto

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

Model Produtoimagem

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 [▶]
        }
      ]
  • Is there anything in your Image Model that might be converting everything to Array?

  • Put the output of dd($product); inside the same looping

  • I changed the post and put more information.

  • [SOLVED] It was giving error, because some products did not have image. I just didn’t understand why when I listed with "->" it gave error and with [' '] it worked.

  • The hint I give is to always print the variable similarly to what I suggested in the previous comment, only the object variable without the attributes

No answers

Browser other questions tagged

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