1

I have a product table and stock table. In stock table data about product sale and purchase are stored. I need to show the stock of every product base on purchase and sale. So I need to call a model function with product Id in vuejs template to calculate the stock quantity of the product. How to do this, or is there any alternative way? please help me out.

My product controller function is-

public function stock() {
    return Product::with(['category', 'stock'])->get();
}

My product model function is-

public function stock($id){
    $purchase_quantity = Stock::where([['product_id', $id], ['stock_type', 'purchase']])->sum('quantity');
    $sale_quantity = Stock::where([['product_id', $id], ['stock_type', 'sale']])->sum('quantity');
    return $purchase_quantity - $sale_quantity;
}

My vuejs template code where in every v-for iteration I want to call the model function-

   <tr v-for="product in products.data" :key="product.id">
      <td>{{ product.id }}</td>
      <td>{{ product.category.name }}</td>
      <td>{{ product.name }}</td>
      <td>{{ product.unit }}</td>
      <td>{{ product.stock(product.id) }}</td>
   </tr>

Here product.stock(product.id) is not working. It shows the error- Too few arguments to function App\Models\Product::stock(), 0 passed

1
  • 1
    Remove the id parameter from your method definition stock($id), then use $this->id instead of $id in your method. ['product_id', $id] => ['product_id', $this->id] Commented Mar 24, 2021 at 2:48

1 Answer 1

2

you need to use accessor in this case so

in Product.php


protected $appends = ['stocks'];

/**
 * Get the Product's stock
 *
 * @return int
 */
public function getStocksAttribute()
{
    $purchase_quantity = Stock::where([['product_id', $this->id], ['stock_type', 'purchase']])->sum('quantity');
    $sale_quantity = Stock::where([['product_id', $this->id], ['stock_type', 'sale']])->sum('quantity');
    return $purchase_quantity - $sale_quantity;
}

then in side javascript you can you can get stock in each product row like product.stocks

your vuejs code will be like this

<tr v-for="product in products.data" :key="product.id">
    <td>{{ product.id }}</td>
    <td>{{ product.category.name }}</td>
    <td>{{ product.name }}</td>
    <td>{{ product.unit }}</td>
    <td>{{ product.stocks }}</td>
</tr>

ref link https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

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

1 Comment

I follow your instruction and In controller function I changed Product::with(['category', 'stock'])->get() => Product::with('category')->get(). It's working. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.