ameenmathers's avatar

Invalid argument supplied for foreach()

Hey there laracasts community, I have been getting this error trying to upload a file, on my phpmyadmin the rest of fields have inserted into the db. this is my code.

cs\project\app\Http\Controllers\HomeController.php

// try{ $ctid = $request->input('ctid');

    $contract = new contract();
    $contract->date_serviced= $request->input('date_serviced');
    $contract->contract_date= $request->input('contract_date');
    $contract->location_desc = $request->input('location_desc');
    $contract->rate = $request->input('rate');
    $contract->contract_expiration_date= $request->input('contract_expiration_date');
    $contract->past_due_penalty= $request->input('past_due_penalty');
    $contract->billing_mail_address= $request->input('billing_mail_address');
    $contract->billing_email_address= $request->input('billing_email_address');
    $contract->billing_contact_name= $request->input('billing_contact_name');
    $contract->billing_contact_phone= $request->input('billing_contact_phone');
    $contract->account_number= $request->input('account_number');
    $contract->signed= $request->input('signed');
    $contract->save();

    foreach ( $request->file( 'pdfs' ) as $item ) {
        $rand          = Str::random( 5 );
        $inputFileName = $item->getClientOriginalName();
        $item->move( "uploads", $rand . $inputFileName );

        $pdf      = new pdf();
        $pdf->url = url( 'uploads/' . $rand . $inputFileName );
        $pdf->cid = $contract->cid;
        $pdf->save();
    }
0 likes
2 replies
theFinalArbiter's avatar

Are you sure $request->file( 'pdfs') always resolves to an array_expression? Can you put it in a try clause and log the content if it fails?

ameenmathers's avatar

I have tried that, although it is now solved

if($request->hasFile('pdfs')){ foreach ($request->file('pdfs') as $item) { $rand = Str::random(5); $inputFileName = $item->getClientOriginalName(); $item->move("uploads", $rand . $inputFileName);

            $pdf = new pdf();
            $pdf->url = url('uploads/' . $rand . $inputFileName);
            $pdf->cid = $contract->cid;
            $pdf->save();
        }
    }

Please or to participate in this conversation.