user3485442
user3485442

Reputation:

Total price calculation by quantity

I know this is a very basic question. But I didn't find the answer on the internet.

Here is my database:

        $table->string('title');
        $table->integer('quantity');
        $table->double('price');
        $table->double('total')->nullable();

I just want to calculate the total price by multiplying price * quantity.

Where should I do this? In controller or model?

Here is the controller:

        Item::create([
        'quantity' => $request->get('quantity'),
        'price' => $request->get('price'),
    ]);

Thanks

Upvotes: 1

Views: 3247

Answers (3)

Josh Rumbut
Josh Rumbut

Reputation: 2710

In the model, so the method can be reused in multiple routes/controllers. Something like this:

public function setTotal() {
    $this->total = $this->price * $this->quantity;
}

Then in the controller:

$item = new Item();
$item->price = 10.0;
$item->quantity = 5;
$item->setTotal();
$item->save();

You can add setTotal() to an override of the save() method or to the setters of the quantity and price fields, then you won't need to call it explicitly in the controller. There are a lot of options here, I am just showing one workable one.

Upvotes: 1

Jems
Jems

Reputation: 1706

you can calculate it on your controller or you can calculate in on your model. If you want to use model

go to your app\Item.php and add this

class Item extends Model {

public function setTotalAttribute()
{
    $this->total = $this->quantity * $this->price; 
}

public function getTotalAttribute($value)
{
    return $value;
}

}

and this is the controller

$item = new Item();
$item->title = $request->title;
$item->price = $request->price;
$item->quantity = $request->quantity;
$item->save();

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try in controller like:

DB::table('yourtablename')->select(DB::raw('(price * quantity) as totalPriceQuantity'))->get();

Upvotes: 0

Related Questions