1

I am having a difficulty accessing the array with json values in it. The values came from another table where I have established a relationship with another table. However, I cannot figure out how to access it correctly. Here is my code.

Model relationship between product and inventory.

Product

 public function inventory(){
    return $this->hasMany('App\InventoryRecord\InventoryRecord');
}

Inventory

public function products(){
     return $this->belongsTo('App\Product\Product','product_id');
}

View

 @foreach($products as $val)

    <?php //$quantity[$i++] = $val->id; ?>

       <tr class="tbl-prod-row">
         <td><input type='checkbox' style='width:30px; height:20px;' class='radio_check_all prod-id-checkbox' id='radio_check_all prod-id-checkbox' value="{{ $val->id }}"></td>
         <td style="display:none;">{{ $val->id }}</td>
         <td style="display:none;">{{ $val->category }}</td>
         <td>{{ $val->pharmaceutical }}</td>
         <td>{{ $val->description }}</td>
         <td>{{ $val->type }}</td>
         <td>{{ $val->unit }}</td>
         <td>{{ $val->price }}</td>
         <td>{{ $val->created_at }}</td>
         <td>{{ $val->po_status }}</td>
         <td>{{ $val->inventory }}</td>

        </tr>

    @endforeach

enter image description here

There is no error shown here but everytime I wanted to access some values in the array by changing the $val->inventory to $val->inventory->quantity, it return an error.

enter image description here

Please help me with this. Thanks a lot.

1 Answer 1

1

That happen because product has many inventory as defined in product model :

$this->hasMany('App\InventoryRecord\InventoryRecord');

So when you call $val->inventory it will return a collection of inventories as described in the error returned in log Undefined property ../Collection::$quantity because you're trying to get attribute from collection.

You have to specify the inventory you want to get the quentity from, e.g :

$val->inventory->first()->quantity
$val->inventory[0]->quantity

Or you could define new method in the model that return the total of product inventory quantities, e.g :

public function inventoriesQuantity(){
   $quantite = 0

   foreach($this->inventory as $inventory){
       $quantity += $inventory->quantity;
   }

   return $quantite;
}

Then call it instead of $val->inventory :

<td>{{ $val->inventoriesQuantity() }}</td>

NOTE : function inventory() in product model should be inventories() because it will return a collection of inventories.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.