Home > Enterprise >  invalid argument supplied for foreach in laravel while working with vue js
invalid argument supplied for foreach in laravel while working with vue js

Time:12-25

I want to store my data in database for cashout details and cashout expenses table. For Cashoutdetails, data is being stored where as it returns error for cashout expenses table. Below is my code for controller --

  $date = Carbon::parse($request->input('recorded_date'));
        if($request->hasFile('bank_receipt')) {
            $file = $request->file('bank_receipt');
            $extension = $file->getClientOriginalExtension(); // getting image extension
            $filename =time().'.'.$extension;
            $file->move('../storage/app/cashoutdetails/'. $date->year .'/' . $date->format('M') . '/' ,$filename);
        }

        $cashout_details = CashOutDetail::create([
            'user_id' => Auth::user()->id,
            'store_id' => $request->store_id,
            'recorded_date' => $request->recorded_date,
            'closing_report_total' => $request->closing_report_total,
            'total_deposit' => $request->total_deposit,
            'difference' => $request->difference,
            'prepared_by' => $request->prepared_by,
            'deposited_by' => $request->deposited_by,
            'deposit_date' => $request->deposit_date,
            'reference_number' => $request->reference_number,
            'bank_receipt'=> $filename,
            'comments' => $request->comments
        ]);
        $comments = $request->cashoutexpenses;
        //return $comments;
        if (! empty($comments)) 
        {
            //return $comments;
            foreach($comments as $c => $value) {
                $cashout_comments = new CashOutExpenses;
                $cashout_comments->cashout_id = $cashout_details->id;
                $cashout_comments->amount = $c['amount'];
                $cashout_comments->comment = $c['comment'];
                $cashout_comments->save();
            }  
        }
        else 
        {
            return 'test';
        }
        return response()->json([
            'message' => 'Details added!',
        ], 201);

If i check for $comments

it gives me result as {"cashoutexpenses":[{"amount":"100","comment":"exp"}]}

where as if i run forloop , it gives result as Invalid argument supplied for foreach()

CodePudding user response:

I think you should json_decode your $comments first then you can use foreach to it

CodePudding user response:

All it required json_decode , exactly as below .

$comments = json_decode($request->cashoutexpenses, true);

Earlier i was using only json_decode along with one parameter without true keyword which was not working

  • Related