Emma Mfinanga
Emma Mfinanga

Reputation: 51

take variable from map function in laraval

I want to check if the requested qty is less than, so How can i take the variable closed_balance in the map function and use on the if condition as per my below code,

i tried to used like this if($item->closing_balance < $qty) by get the error

Undefined variable: closing_balance

Controller code

  $data=$request->all();
       if(count($request->pid) > 0)
       {
        foreach($request->pid as $key=>$v){
            $data2=([
                'order_no'=>$fk,
                'pid'=>$request->pid [$key],
                'sid'=>$request->sid,
                'qty'=>$request->qty [$key],
            ]);

            $pid= $request->pid [$key];
            $qty=$request->qty [$key];

            $check_balance=DB::table('products')
                      ->selectRaw('sum(stocks.qty) as totalstock')
                      ->selectRaw('sum(loadings.qty) as totalloading')
                      ->join('stocks','stocks.pid','=','products.id')
                      ->join('loadings','loadings.pid','=','products.id')
                      ->where('stocks.pid','=',$pid)
                      ->where('loadings.pid','=',$pid)
                      ->get() ->map(function ($item) {
                        $item->totalstock = $item->totalstock ?? 0;
                        $item->totalloading = $item->totalloading ?? 0;
                        $item->closing_balance = abs($item->totalstock - $item->totalloading);
                        return $item;
                    });

        //check if quatity is less than requested
            if($closing_balance  < $qty){

               return redirect()->back()
               ->withErrors(['The stock quantity is less, Please check your stock quantity! ']);
           }
           else{

            Loading::create($data2);
        }

Upvotes: 1

Views: 302

Answers (1)

Robert Kujawa
Robert Kujawa

Reputation: 997

I'm not exactly sure what you are trying to accomplish here, because the map function is iterating through every single item in the collection, and looks like closing_balance is an attribute of every item, so not sure what exactly you would like to compare.

You can add an '&' ampersand before a variable to your function inside the use() statement in order to use and modify that variable inside and outside your map function.

I believe you want to sum up all the the closing balances of each item, so you can do something like this in your map function.

$collection->map(function ($item) use (&$closing_balance) {
    $item->totalstock = $item->totalstock ?? 0;
    $item->totalloading = $item->totalloading ?? 0;
    $item->closing_balance = abs($item->totalstock - $item->totalloading);

    $closing_balance += $item->closing_balance;

    return $item;
});

// Now you can use $closing_balance variable.
if($closing_balance  < $qty){
    // Your code...
}

Upvotes: 1

Related Questions