Adding total price calculation of an order item for an order - cruds of order

In this previous post where order addition tutorial was posted we have not implemented one step where we created a text input field named product_cost but kept it empty and readonly.

We kept it that way because our intention was to fill the value here dynamically by ajax call by taking form inputs - quantity, frame_witdth_id, total_sq_feet and product_id.

Now if we pass these values in JS code for ajax calling we need to implement following calculation in server and return the result back in JS code to populate that empty readonly input field. So, the calculation is mentioned below

total_price_of_order = quantity x total_sq_feet x ( product_price + ( product_price x frame_width_percentage ) )

So, following code snippets are implemented step by step to achieve this result.

Step 01: Creating OrderItemController with artisan command

php artisan make:controller OrderItemController

Step 02: Adding route for method calculateOrderPrice() in OrderItemController.php in routes/web.php like below

Route::group(['middleware'=> [ 'auth']], function() {

    Route::resource('orders', \App\Http\Controllers\OrderController::class);
    
    Route::group(['middleware'=> ['is_admin']], function() {
        Route::resource('users', \App\Http\Controllers\UserController::class);

        Route::post('/products/save_order/{product}', [\App\Http\Controllers\ProductController::class, 'saveOrder'])->name('products.save_order');
        Route::post('/profiles/save_order/{profile}', [\App\Http\Controllers\ProfileController::class, 'saveOrder'])->name('profiles.save_order');
        Route::post('/frame_widths/save_order/{frame_width}', [\App\Http\Controllers\FrameWidthController::class, 'saveOrder'])->name('frame_widths.save_order');

        Route::resource('products', \App\Http\Controllers\ProductController::class);
        Route::resource('profiles', \App\Http\Controllers\ProfileController::class);
        Route::resource('frame_widths', \App\Http\Controllers\FrameWidthController::class);

        Route::post('/order_items/cal_cost', [\App\Http\Controllers\OrderItemController::class, 'calculateOrderPrice'])->name('calCost');
    });    

}); 

Step 03: Adding calculatePercentage() and calculateOrderPrice() in OrderItem.php model like below

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OrderItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id', 'product_id', 'profile_id', 'frame_width_id' ,'width', 'height', 'total_square_feet', 'quantity', 'cost', 'additional_request'
    ];

    public function order() {
        return $this->belongsTo( Order::class );
    } 
    
    public function product() {
        return $this->belongsTo( Product::class );
    }  
    
    public function fwidth() {
        return $this->belongsTo( FrameWidth::class, 'frame_width_id' );
    }    

    public function calculateTotSqFeet( $width, $height ) {
        return number_format(( $width * $height )/144,2);
    }

    public function calculatePercentage( $price, $percentage ) {
        $pricePercentage = $price * ( $percentage / 100 );
        $totalPrice      = $price + $pricePercentage;
        return $totalPrice;
    }

    public function calculateOrderPrice( $params = [] ) { //dd($params);
        if( !empty($params) ) {
            $this->quantity = $params['quantity'];
            $this->cost = $params['cost'];
            $this->percentage = $params['percentage'];
            $this->total_square_feet = $params['total_square_feet'];
        }
        return $this->quantity * $this->calculatePercentage( $this->cost, $this->percentage ) * $this->total_square_feet;
    }    

}

Step 04: Adding calculateOrderPrice() in OrderItemController

function calculateOrderPrice ( Request $request ) {
	$fwidth = FrameWidth::where('id',$request->fwidth)->first(); 
	$product = Product::where('id',$request->productId)->first();

	$item = new OrderItem();
	$cost = $item->calculateOrderPrice( ['quantity' => $request->quantity, 'cost' => $product->cost, 'percentage' => $fwidth->percentage, 'total_square_feet' => $request->total_square_feet  ] );

	return response()->json( number_format($cost,2) ,200);
}   

Now, while order addition if we input the values of quantity, frame_witdth_id, total_sq_feet ( it is another calculation of two inputs - width and height ( width * height / 144 ) )  and product_id that empty input field named product_cost will be populated. Hence, we will get the totalprice of the orderitem for that order.

Related Posts


Building mini ecommerce in Laravel

Listing rows of users - crud

Adding user data - crud of users

Editing user data - crud of users

Deleting user data - crud of users

Listing rows of products - crud

Listing rows of profiles - crud

Listing rows of orders - crud

Listing rows of order items - crud