Search code examples
eloquentlaravel-5.3

Product with tags with pivot how can i access relationship


The following $product returns Product object. But how can i access the relations:array "tags" by foreach?

When i do $tags->tags i get the tags of the product table.

Foreach:

foreach ($product as $tags) {

}

Instance:

$product        = Product::with('tags')->where('id',$id)->get();

Output:

Product {#371 ▼
#table: "products"
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [▶]
#original: array:10 [▶]
#relations: array:1 [▼
"tags" => Collection {#399 ▼
  #items: array:2 [▼
    0 => Tag {#397 ▼
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:4 [▶]
      #original: array:6 [▶]
      #relations: array:1 [▶]
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }

Solution

  • Use first instead of get to get a model instance instead of collection.

    $product = Product::with('tags')->where('id', $id)->first();
    

    Then you can loop through each tag.

    foreach ($product->tags as $tag) {
        // do something
    }