Skip to content
Advertisement

How to call Laravel Model function with parameter into Vuejs (for calculating stock Qunatity)?

I have three model 1.Fertilizer, 2. Fertilizer Stock, 3.Fertilizer Sale. 2 & 3 have foreign key relation(fertilizer_id) & mysql quantity column . I want to calculate individual Fertilizer stock quantity in my fertilizer model and append with fertilizerController in inertia index page. What’s Wrong with my code?

Controller

    /**
 * Display a listing of the resource.
 *
 * @return IlluminateHttpResponse
 */
public function index( Request $request)
{
    return Inertia::render('Fertilizers/Index', [
        'fertilizers' => Fertilizer::with('stocks')
        ->filter($request->all())
            ->sorted()
            ->paginate()
            ->withQueryString(),
        'query'  => $request->all(),
    ]);
}

Model

    protected $appends = ['stocks'];
/**
 * Determines one-to-many relation
 *
 * @return IlluminateDatabaseEloquentRelationsBelongsTo
 */
public function units()
{
   return $this->belongsTo(Unit::class);
}

Stock Function

public function getStocksAttribute(){
$stock_quantity = FertilizerStock::where(['fertilizer_id', $this->id])->sum('quantity');
$sale_quantity = FertilizerSell::where(['fertilizer_id', $this->id])->sum('quantity');
return $stock_quantity - $sale_quantity;}

Advertisement

Answer

Add this on your Fertilizer Model.

    public function getStockAttribute()
{
    $fertilizerId= $this->id;
    $fertilizerStock = FertilizerStock::where('fertilizer_id',$fertilizerId)->sum('quantity');
    $fertilizerSells = FertilizerSell::where('fertilizer_id',$fertilizerId)->sum('quantity');
    return $fertilizerStock-$fertilizerSells;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement