Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a calculated value as if it's a column value in Laravel model?

Tags:

php

laravel

I have a project that has a project model which looks like this:

class Product extends Model
{
    public $timestamps = true;
    protected $guarded = ['id'];
    protected $table = 'products';
    protected $hidden = ['created_at', 'updated_at'];
    protected $fillable = ['name', 'category_id', 'units', 'b_price', 's_price', 'warn_count', 'added_by'];

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function stock(){
        $product_id = $this->id;
        $filter = ['product_id' => $product_id];
        //STOCK PLUS
        //credit purchases
        $cr_purchases = CreditPurchase::where($filter)->sum('qty');
        //purchases
        $purchases = Purchase::where($filter)->sum('qty');
        //returns in
        $re_in = ReturnIn::where($filter)->sum('qty');
        //STOCK MINUS
        //credit sales
        $cr_sales = CreditSale::where($filter)->sum('qty');
        //sales
        $sales = Sale::where($filter)->sum('qty');
        //returns out
        $re_out = ReturnOut::where($filter)->sum('qty');
        //damaged
        $damaged = DamagedProduct::where($filter)->sum('qty');
        return $cr_purchases + $purchases + $re_in - ($cr_sales + $sales + $re_out + $damaged);
    }
}

As can be seen stock is a calculated value for each model. I wish to make queries based on it as though it were a column of the products table.

like image 903
Mutai Mwiti Avatar asked Sep 06 '16 17:09

Mutai Mwiti


1 Answers

Method 1
Change the stock method to be an Laravel model accessor.

public function getStockAttribute(){
   //code logic
}

Fetch the results as a Collection and perform filters on the 'stock; attribute
I would do something like.

Products::where('product','like','miraa') //where
->get()
->filter(function($item) {
    return $item->stock > 100;
});

Read about filtering collections

Method 2
Use dynamic query scopes See scopes in laravel.

public function scopeAvailbaleStock($query, $type)
{
    return $query->where('type', $type);
    // could perform filters here for the query above
}

Fetch using scope

$users = Products::available_stock()->get();

Method 3 I saw out this package jarektkaczyk/eloquence

public function scopeWhereStock($query, $price, $operator = '=', $bool = 'and'){
    $query->where('info1', $operator, $price, $bool);
   }

// then
Products::whereStock(25); // where('info1', 25);
Products::whereStcok(25, '>'); // where('info1', '>', 25);
Products::whereStock(25, '=', 'or'); // orWhere('info1', 25);

Howerever, i would recomend to use method 1 or 2. The 3rd solution works but not sure if it is the best

like image 61
Samuel Dervis Avatar answered Nov 15 '22 00:11

Samuel Dervis